连接可以是单例,您可以共享它以进行多次发送。
该通道应该是一个用于线程的通道。
你的代码可以是:
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();
}
您可以决定为每个发布创建和销毁一个通道,或者为您的线程创建它并始终重复使用相同的通道。
EDIT**为了创建单例,请阅读此处:http://javarevisited.blogspot.it/2012/12/how-to-create-thread-safe-singleton-in-java-example.html 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;
}
}
这是创建单例的一种方法
private void send(String routingKey, String message) throws Exception {
Connection connection = MySingletonConnection().getInstance().getConnection();