这个RabbitMQ代码是否会导致内存泄漏

时间:2016-03-16 05:44:11

标签: java rabbitmq amqp

我有以下代码段。如果RabbitMQ服务器掉线,则连接似乎返回null并建立新连接。我怀疑重复尝试重新连接服务器正在耗尽内存,但我不确定原因。如何处理丢失的连接(服务器不可用)?

public Connection getConnection( ) {
    if (myConnection == null) {
        start();
    }
    return myConnection;
}

private void start() {
    log.debug("Building AMQP Connection");

    ConnectionFactory factory = new ConnectionFactory();
    String ipAddress = applicationConfiguration.getAMQPHost();
    String user = applicationConfiguration.getAMQPUser();
    String password = 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) {
        log.error("Unable to initialise AMQP Connection.");
        e.printStackTrace();
    }

    myConnection.addBlockedListener(new BlockedListener() {
        public void handleBlocked(String reason) throws IOException {
            // Connection is now blocked
            log.warn("Message Server has blocked.  It may be resource limitted.");
            blocked = true;
        }

        public void handleUnblocked() throws IOException {
            // Connection is now unblocked
            log.warn("Message server is unblocked.");
            blocked = false;
        }
    });
}

public Boolean isBlocked() {
    return blocked;
}

代码是邮件系统的一部分,它将绑定的邮件重定向到传出的AMQP队列。每次接收到绑定消息(以每秒20到30的速率)时,都会调用getConnection方法。如果AMQP服务器已关闭,则仍会调用该方法,并尝试构建队列。它失败了,每次失败都会导致一个看似占用更多内存的异常。

0 个答案:

没有答案