且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每次发送消息都需要重建RabbitMQ连接吗

更新时间:2023-02-05 12:06:24

连接可以是单例,您可以共享它以进行多次发送.通道应该是一个线程.

The connection could be a singleton, and you can share it for multiple send. The channel should be one for thread.

你的代码可能是:

private void send(String routingKey, String message) throws Exception { 
     Connection connection = MyConnection().getInstance();

    Channel channel = connection.createChannel();
    channel.exchangeDeclare(exchange, exchangeType);
    channel.basicPublish(exchange, routingKey, null, message.getBytes());
    log.debug(" [AMQP] Sent message with key {} : {}",routingKey, message);
    channel.close();
}

您可以决定为每个发布创建和销毁一个频道,或者为您的线程创建它并始终重用相同的频道.

You can decide to create and destroy a channel for each publish, or create it for your thread and reuse always the same channel.

编辑**为了创建一个单例阅读这里:http://javarevisited.blogspot.it/2012/12/how-to-create-thread-safe-singleton-in-java-example.html

EDIT** In order to create a sigleton read here: http://javarevisited.blogspot.it/2012/12/how-to-create-thread-safe-singleton-in-java-example.html

public class MySingletonConnection{
    private static final MySingletonConnection INSTANCE = new MySingletonConnection();
    private Connection myConnection;
    private Singleton(){ 
      // here you can init your connection parameter
    }

    public static MySingletonConnection getInstance(){
        return INSTANCE;
    }

 public Connection getConnection( ) {
    return connection;
}
}

这是创建单例的一种方式

This is one way to create a Singleton

private void send(String routingKey, String message) throws Exception { 
     Connection connection = MySingletonConnection().getInstance().getConnection();