RabbitMQ Java Клиентский канал закрывается при создании - PullRequest
0 голосов
/ 06 мая 2020

Я написал этот класс для чтения и записи в каналы RabbitMQ. Я удалил несколько строк, чтобы сократить код.

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class RabbitMQ {

  /**
   * Creates a new RabbitMQ Channel binding to localhost
   * @param channel The Queue name the Channel binds to
   * @return The newly created Channel
   * @throws IOException
   * @throws TimeoutException
   */
  private static Channel createChannel(String channel) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");

    try(Connection connection = factory.newConnection(); Channel newChannel = connection.createChannel()) {
      newChannel.queueDeclare(channel, true, false, false, null);
      return newChannel;
    }
  }

  /**
   * Writes to a Queue
   * @param channel The name of the queue
   * @param message The message to send
   * @throws IOException
   * @throws TimeoutException
   */
  public static void write(String channel, String message) throws IOException, TimeoutException {
    Channel channelOut = createChannel(channel);

    channelOut.basicPublish("", message, null, message.getBytes());
  }
}

Чтобы проверить функцию, я назвал это:

new Thread(() -> {
      try {
        RabbitMQ.write("test", "testmessage");
      } catch (IOException | TimeoutException e) {
        e.printStackTrace();
      }
}).start();

Хотя при выполнении консоль выдает это исключение:

Exception in thread "Thread-0" com.rabbitmq.client.AlreadyClosedException: channel is already closed due to clean channel shutdown; protocol method: #method<channel.close>(reply-code=200, reply-text=OK, class-id=0, method-id=0)
    at com.rabbitmq.client.impl.AMQChannel.ensureIsOpen(AMQChannel.java:258)
    at com.rabbitmq.client.impl.AMQChannel.transmit(AMQChannel.java:427)
    at com.rabbitmq.client.impl.ChannelN.basicPublish(ChannelN.java:710)
    at com.rabbitmq.client.impl.ChannelN.basicPublish(ChannelN.java:685)
    at com.rabbitmq.client.impl.ChannelN.basicPublish(ChannelN.java:675)
    at com.rabbitmq.client.impl.recovery.AutorecoveringChannel.basicPublish(AutorecoveringChannel.java:197)
    at de.flow.command.rabbitmq.RabbitMQ.write(RabbitMQ.java:52)

RabbitMQ.java:52 относится к newChannel.queueDeclare(channel, true, false, false, null);

Когда я перечисляю все активные очереди с помощью ./rabbitmqctl.bat list_queues , отображаются очереди, созданные кодом.

Не понимаю, почему закрывается без ошибок при создании.

1 Ответ

0 голосов
/ 07 мая 2020

Я решил проблему, убрав «попробовать» в методе createChannel-Method

private static Channel createChannel(String channel) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setHost("localhost");

    Connection connection = factory.newConnection();
    Channel newChannel = connection.createChannel();

    newChannel.queueDeclare(channel, false, false, false, null);

    return newChannel;
  }
...