java如何为ActiveMQ队列创建Spring引导使用者?
我正在学习ActiveMQ,到目前为止,我已经制作了一个简单的Spring Boot producer+consumer应用程序(在本问题中称之为App1),它与ActiveMQ的本地实例进行通信,一切正常
现在我正在尝试运行一个不同的Spring Boot应用程序(在同一台计算机上,但在确保App1未运行后),该应用程序只有一个使用者(没有生产者),但当我启动此应用程序时,队列中的消息(我使用修改后的App1放入,其中我删除了应用程序的使用者部分)不会被拾取。在App1中,消息发布后,消费者立即打印出系统。out print语句,但在这个仅限消费者的应用程序中并非如此。下面是我的侦听器组件类:
package com.demo.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer {
@JmsListener(destination = "testqueue")
public void consume(String message) {
System.out.println("Picked up message: " + message);
}
}
为了达到预期的行为,我需要做哪些改变
App1application.properties
文件:
spring.activemq.in-memory=false
spring.activemq.pool.enabled=false
server.port=9000
activemq.broker-url=tcp://localhost:61616
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
security.basic.enabled=false
management.security.enabled=false
App1JmsConfig类
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
@Configuration
public class JmsConfig {
@Value("${activemq.broker-url}")
private String brokerUrl;
@Bean
public Queue queue() {
return new ActiveMQQueue("testqueue");
}
@Bean
public ActiveMQConnectionFactory activeMQConnectionFactory() {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
factory.setBrokerURL(brokerUrl);
return factory;
}
@Bean
public JmsTemplate jmsTemplate() {
return new JmsTemplate(activeMQConnectionFactory());
}
}
App1制作人级
import javax.jms.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rest/publish")
public class ProducerResource {
@Autowired
JmsTemplate jmsTemplate;
@Autowired
Queue queue;
@GetMapping("/{message}")
public String publishMessage(@PathVariable("message") final String message) {
jmsTemplate.convertAndSend(queue, message);
return "Published successfully";
}
}
App1消费者类与我在仅消费者应用程序(上面列出)中使用的类相同
# 1 楼答案
对于您的消费者应用程序,您确实需要添加池连接工厂&;用于消费者JMStemplate开始接收消息的JMS消息侦听器工厂
您可以阅读更多关于它的信息here