Каков вариант использования BrokerService в ActiveMQ и как его правильно использовать

Я новичок в ActiveMQ. Я пытаюсь изучить и проверить, как это работает, проверив пример кода, предоставленный Apache по этой ссылке: -

http://activemq.apache.org/how-should-i-implement-request-response-with-jms.html

    public class Server implements MessageListener {
        private static int ackMode;
        private static String messageQueueName;
        private static String messageBrokerUrl;

        private Session session;
        private boolean transacted = false;
        private MessageProducer replyProducer;
        private MessageProtocol messageProtocol;

        static {
            messageBrokerUrl = "tcp://localhost:61616";
            messageQueueName = "client.messages";
            ackMode = Session.AUTO_ACKNOWLEDGE;
        }

        public Server() {
            try {
                //This message broker is embedded
                BrokerService broker = new BrokerService();
                broker.setPersistent(false);
                broker.setUseJmx(false);
                broker.addConnector(messageBrokerUrl);
                broker.start();
            } catch (Exception e) {
                System.out.println("Exception: "+e.getMessage());
                //Handle the exception appropriately
            }

            //Delegating the handling of messages to another class, instantiate it before setting up JMS so it
            //is ready to handle messages
            this.messageProtocol = new MessageProtocol();
            this.setupMessageQueueConsumer();
        }

        private void setupMessageQueueConsumer() {
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(messageBrokerUrl);
            Connection connection;
            try {
                connection = connectionFactory.createConnection();
                connection.start();
                this.session = connection.createSession(this.transacted, ackMode);
                Destination adminQueue = this.session.createQueue(messageQueueName);

                //Setup a message producer to respond to messages from clients, we will get the destination
                //to send to from the JMSReplyTo header field from a Message
                this.replyProducer = this.session.createProducer(null);
                this.replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

                //Set up a consumer to consume messages off of the admin queue
                MessageConsumer consumer = this.session.createConsumer(adminQueue);
                consumer.setMessageListener(this);
            } catch (JMSException e) {
                System.out.println("Exception: "+e.getMessage());
            }
        }

        public void onMessage(Message message) {
            try {
                TextMessage response = this.session.createTextMessage();
                if (message instanceof TextMessage) {
                    TextMessage txtMsg = (TextMessage) message;
                    String messageText = txtMsg.getText();
                    response.setText(this.messageProtocol.handleProtocolMessage(messageText));
                }

                //Set the correlation ID from the received message to be the correlation id of the response message
                //this lets the client identify which message this is a response to if it has more than
                //one outstanding message to the server
                response.setJMSCorrelationID(message.getJMSCorrelationID());

                //Send the response to the Destination specified by the JMSReplyTo field of the received message,
                //this is presumably a temporary queue created by the client
                this.replyProducer.send(message.getJMSReplyTo(), response);
            } catch (JMSException e) {
                System.out.println("Exception: "+e.getMessage());
            }
        }

        public static void main(String[] args) {
            new Server();
        }
    }

Мое замешательство по поводу messageBrokerUrl = "tcp://localhost:61616"; Вы знаете, что служба ActiveMQ по умолчанию работает на порту 61616. Почему в этом примере выбран тот же порт. Если я попытаюсь запустить код, это вызовет прием как: Исключение: не удалось выполнить привязку к сокету сервера: tcp://localhost:61616 из-за: java.net.BindException: адрес уже используется: JVM_Bind

Возможно, если я изменю номер порта, я смогу выполнить код.

Подскажите, пожалуйста, почему в примере так и как работать с BrokerService.


person masiboo    schedule 23.09.2017    source источник


Ответы (1)


Служба BrokerService в этом примере пытается создать в памяти брокера ActiveMQ для использования в этом примере. Учитывая ошибку, которую вы видите, я предполагаю, что у вас уже есть брокер ActiveMQ, работающий на машине, которая привязана к порту 61616, поскольку это порт по умолчанию, и поэтому они конфликтуют. Вы можете либо остановить внешний посредник и запустить пример, либо изменить пример, чтобы не запускать встроенный посредник и полагаться только на экземпляр внешнего посредника.

Встроенные брокеры отлично подходят для модульного тестирования или для создания примеров, которые не требуют от пользователя установки и запуска брокера.

person Tim Bish    schedule 25.09.2017
comment
Встроенный BrokerService против установленного брокера ActiveMQ? Есть ли особенности одинаковые или разные? Можно также упомянуть любые плюсы и минусы обоих этих - person masiboo; 25.09.2017
comment
Это для обсуждения темы переполнения стека, я ответил на ваш основной вопрос, другую информацию следует запросить в сообществе ActiveMQ. - person Tim Bish; 25.09.2017
comment
Я пересматриваю ActiveMQ, и мне нужно запустить пример, чтобы вернуться к скорости. Та же путаница и использование того же примера ActiveMQ. Чего я не заметил в этом примере, так это того, что setupMessageQueueConsumer() настраивает BrokerService, но эта часть не нужна, если у вас уже запущен ActiveMQ. Поэтому я удалил весь этот блок try-catch из конструктора и оставил только две строки для настройки для потребителя очереди сообщений. Задним числом это очевидно, но этот ответ привел меня прямо к тому, что я упустил из виду в коде. [голосование] Ура! - person Pete Kelley; 20.04.2021