新建一个SpringBoot项目,版本为:2.2.6.RELEASE,整合ActiveMq需要引用的pom为依赖及配置文件如下:
org.springframework.boot spring-boot-starter-activemq
#mq spring.activemq.broker-url: failover:(tcp://127.0.0.1:61616)?maxReconnectAttempts=3&maxReconnectDelay=5000 spring: activemq: user: admin password: admin packages: trust-all: true spring.activemq.in-memory: false #true表示使用连接池;false时,每发送一条数据创建一个连接 spring.activemq.pool.enabled: true #连接池最大连接数 spring.activemq.pool.max-connections: 10 #空闲的连接过期时间,默认为30秒 spring.activemq.pool.idle-timeout: 30000 #强制的连接过期时间,与idleTimeout的区别在于:idleTimeout是在连接空闲一段时间失效,而expiryTimeout不管当前连接的情况,只要达到指定时间就失效。默认为0,never spring.activemq.pool.expiry-timeout: 0 #mq end jms.card.active.message.handler.destination: jms.card.active.message.handler.destination
发送消息代码如下:
public class CardActiveMessageSender { private static final Logger logger = LoggerFactory.getLogger(CardActiveMessageSender.class); @Value("${jms.card.active.message.handler.destination}") String destinationName; @Resource private JmsMessagingTemplate jmsMessagingTemplate; public void sendMsg(OrdersDto ordersDto){ logger.info("发送入账流水:{}", JsonUtil.objToJson(ordersDto)); String tradeString = JsonUtil.objToJson(ordersDto); jmsMessagingTemplate.convertAndSend(destinationName,tradeString); logger.info("发送入账流水成功"); } }
接受消息代码如下:
public class CardActiveMessageHandler {
private static final Logger logger = LoggerFactory.getLogger(CardActiveMessageHandler.class);
@JmsListener(destination = "${jms.card.active.message.handler.destination}")
public void handleMessage(String request){
try {
logger.info("接受消息如下:{}",request);
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
}
}
按上面的配置启动项目,会报错,错误信息如下:
*************************** APPLICATION FAILED TO START *************************** Description: A component required a bean of type 'org.springframework.jms.core.JmsMessagingTemplate' that could not be found. The following candidates were found but could not be injected: - Bean method 'jmsMessagingTemplate' in 'JmsAutoConfiguration.MessagingTemplateConfiguration' not loaded because Ancestor org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration did not match Action: Consider revisiting the entries above or defining a bean of type 'org.springframework.jms.core.JmsMessagingTemplate' in your configuration.
从报错可以看出jmsMessagingTemplate未被正常注入。
解决方式有两种:
1.增加pom依赖(springboot2.1+时引用):
org.messaginghub pooled-jms
重新编译成功,此方式已经在本地验证通过
如果是springboot2.0及以下版本则引用(本人未验证)
org.apache.activemq activemq-pool
上面两种因为版本不同而引用不同依赖的原因是:两种版本使用连接池时候的连接池对象不一样,2.0以下版本使用的是PooledConnectionFactory,它存在于org.apache.activemq.pool.PooledConnectionFactory,2.1+版本使用的是JmsPoolConnectionFactory,它存在于org.messaginghub.pooled.jms.JmsPoolConnectionFactory。
2.使用@Configuration注入,配置如下:
@Configuration public class MQConfig { @Value("${spring.activemq.broker-url}") private String brokerUrl; @Value("${spring.activemq.user}") private String user; @Value("${spring.activemq.password}") private String password; @Bean public ConnectionFactory connectionFactory(){ ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL(brokerUrl); connectionFactory.setUserName(user); connectionFactory.setPassword(password); return connectionFactory; } @Bean public JmsTemplate genJmsTemplate(){ return new JmsTemplate(connectionFactory()); } @Bean public JmsMessagingTemplate jmsMessageTemplate(){ return new JmsMessagingTemplate(connectionFactory()); } }
重启启动项目成功,已在本地测试通过。
测试结果:
2020-06-29 15:50:50.711 [] [http-nio-8080-exec-1] INFO o.s.web.servlet.DispatcherServlet :Initializing Servlet 'dispatcherServlet' 2020-06-29 15:50:50.720 [] [http-nio-8080-exec-1] INFO o.s.web.servlet.DispatcherServlet :Completed initialization in 8 ms 2020-06-29 15:50:50.831 [] [http-nio-8080-exec-1] INFO c.y.p.d.m.s.CardActiveMessageSender :发送入账流水:{"orderBatchId":123456,"orderId":123456,"status":"1"} 2020-06-29 15:50:50.910 [] [http-nio-8080-exec-1] INFO c.y.p.d.m.s.CardActiveMessageSender :发送入账流水成功 2020-06-29 15:50:50.919 [] [DefaultMessageListenerContainer-1] INFO c.y.p.d.m.h.CardActiveMessageHandler :接受消息如下:{"orderBatchId":123456,"orderId":123456,"status":"1"}