调用channel.close()后关闭RabbitMQ连接

时间:2017-01-13 12:00:01

标签: java rabbitmq

我正在使用Java RabbitMQ Client。我发布了一条消息(basicPublish),然后我关闭了频道。在Consumer中,channel.basicAck抛出异常:

com.rabbitmq.client.AlreadyClosedException: connection is already closed due to connection error; cause: java.util.concurrent.RejectedExecutionException: Task com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable@665de7c7 rejected from java.util.concurrent.ThreadPoolExecutor@35f53993[Running, pool size = 5, active threads = 5, queued tasks = 0, completed tasks = 5]

如果删除channel.close(),则不会再现错误。当我关闭频道时,为什么连接关闭?

已发送消息以进行交换:

Channel channel = connection.createChannel();
Set<String> expectedMessages = new HashSet<>(MESSAGES_COUNT);
for (int i = 0; i < MESSAGES_COUNT; i++) {
    String message = Integer.toString(i);
    channel.basicPublish(
        TEST_EXCHANGE,
        ROUTE_KEY,
        TEXT_PLAIN,
        message.getBytes("UTF-8")
    );
    expectedMessages.add(message);
}
channel.close();

消费者:

try {
    channel.basicAck(deliveryTag, false);
} catch (Exception e) {
    log.error("Error during message handling: " + consumerTag, e);
    channel.basicNack(deliveryTag, false, true);
}

1 个答案:

答案 0 :(得分:0)

问题在于错误的connectionFactory设置。 不正确的:

    executorService = new ThreadPoolExecutor(
            properties.minThreads, properties.maxThreads,
            properties.maxThreadIdle, TimeUnit.SECONDS,
            new SynchronousQueue<>()
    );
    connectionFactory.setSharedExecutor(executorService);

正确的工作:

    executorService = new ThreadPoolExecutor(
            properties.minThreads, properties.maxThreads,
            properties.maxThreadIdle, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>()
    );
    connectionFactory.setSharedExecutor(executorService);