【发布时间】:2023-03-07 17:26:02
【问题描述】:
我正在使用 ActiveMQ,我为一些消息创建了生产者和消费者。
这样我创建了连接,并创建了目的地:
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(username,password,"tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("MyQueue");
这样我创建了生产者并发送消息:
Producer producer = session.createProducer(destination);
producer.send(msgToSend);
我创建了消费者并为它设置了一个监听器(实现 MessageListener 接口的类)
Consumer consumer = session.createConsumer(destination);
consumer.setMessageListener(this);
消费者连接到目的地并正在监听消息。 当它从队列“MyQueue”中获取一些消息时,会触发来自 MessageListener 的 onMessage() 方法并对消息执行任何我想要的操作。
我的代码工作,我能够产生和消费消息。生产者在服务器上,消费者在客户端(一个单独的项目)。
为了让它工作,我从here 安装了 apache-activemq-5.14.4-bin.zip。我将依赖项放在 pom.xml 中:
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.14.0</version>
</dependency>
嗯,现在安装的 ActiveMQ 是一个在计算机启动时启动的服务。我不想将它安装为服务,而是在 java 中以编程方式启动和停止它。例如,按下 Start 按钮并执行代码来启动它,然后按下 Stop 并停止它。
我能否以编程方式实现而不将 ActiveMQ 安装为服务?
【问题讨论】: