【发布时间】:2014-11-27 01:01:23
【问题描述】:
我有一个通过 RabbitMQ 发送 AMQP 消息的应用程序。消息发送是在 http 请求上触发的。最近我注意到有些消息似乎丢失了(就像从未发送过一样)。我还注意到服务器管理的频道列表正在稳步增加。我纠正的第一件事是在不再需要通道后关闭它们。但是,我仍然不确定我的代码结构是否正确以确保交付。下面是两段代码;第一个是管理连接的单例部分(不会在每次调用时重新创建),第二个是发送代码。任何建议/指导将不胜感激。
@Service
public class PersistentConnection {
private static Connection myConnection = null;
private Boolean blocked = false;
@Autowired ApplicationConfiguration applicationConfiguration;
@Autowired ConfigurationService configurationService;
@PostConstruct
private void init() {
}
@PreDestroy
private void destroy() {
try {
myConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Connection getConnection( ) {
if (myConnection == null) {
start();
}
else if (!myConnection.isOpen()) {
log.warn("AMQP Connection closed. Attempting to start.");
start();
}
return myConnection;
}
private void start() {
log.debug("Building AMQP Connection");
ConnectionFactory factory = new ConnectionFactory();
String ipAddress = applicationConfiguration.getAMQPHost();
String password = applicationConfiguration.getAMQPUser();
String user = applicationConfiguration.getAMQPPassword();
String virtualHost = applicationConfiguration.getAMQPVirtualHost();
String port = applicationConfiguration.getAMQPPort();
try {
factory.setUsername(user);
factory.setPassword(password);
factory.setVirtualHost(virtualHost);
factory.setPort(Integer.parseInt(port));
factory.setHost(ipAddress);
myConnection = factory.newConnection();
}
catch (Exception e) {
e.printStackTrace();
}
myConnection.addBlockedListener(new BlockedListener() {
public void handleBlocked(String reason) throws IOException {
// Connection is now blocked
blocked = true;
}
public void handleUnblocked() throws IOException {
// Connection is now unblocked
blocked = false;
}
});
}
public Boolean isBlocked() {
return blocked;
}
}
/*
* Sends ADT message to AMQP server.
*/
private void send(String routingKey, String message) throws Exception {
String exchange = applicationConfiguration.getAMQPExchange();
String exchangeType = applicationConfiguration.getAMQPExchangeType();
Connection connection = myConnection.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchange, exchangeType);
channel.basicPublish(exchange, routingKey, null, message.getBytes());
// Close the channel if it is no longer needed in this thread
channel.close();
}
【问题讨论】:
-
可以从更多线程调用
getConnection( )吗?如果是,则代码不是线程安全的。 -
一个 http 请求进来,最终调用 getConnection() 调用。所以我想它可以。我想通过使它成为一个单例来解决这个问题。改进代码的最佳方法是什么?