springboot整合activemq
一、添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
二、添加配置
#activemq spring.activemq.broker-url=tcp://10.100.1.99:61616 spring.activemq.in-memory=true spring.activemq.user=admin spring.activemq.password=admin spring.activemq.pool.enabled=false
三、生产者和消费者
Producer
package com.dc.sb.web.activemq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.stereotype.Component; import javax.jms.Destination; /** * @author DUCHONG * @since 2018-12-19 11:32 **/ @Component public class Producer { private static final Logger logger = LoggerFactory.getLogger(Producer.class); @Autowired private JmsMessagingTemplate messagingTemplate; public void sendMessage(Destination destination,String text){ messagingTemplate.convertAndSend(destination,text); } }
Consumer
package com.dc.sb.web.activemq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.stereotype.Component; /** * @author DUCHONG * @since 2018-12-19 11:44 **/ @Component public class Consumer { private static final Logger logger = LoggerFactory.getLogger(Consumer.class); @Autowired private JmsMessagingTemplate messagingTemplate; @JmsListener(destination = "helloQueue") public void receiveMessage(String text){ System.out.println("Listener....receive msg....."+text); } }
Controller
package com.dc.sb.web.activemq; import org.apache.activemq.command.ActiveMQQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.jms.Destination; /** * @author DUCHONG * @since 2018-12-19 13:57 **/ @RestController public class ActiveMQController { private static final Logger logger = LoggerFactory.getLogger(ActiveMQController.class); @Autowired private Producer producer; @RequestMapping("/send/msg") public String sendQueueMsg(){ Destination destination=new ActiveMQQueue("helloQueue"); String text="Hello ActiveMQ!"; for (int i=0;i<6;i++){ producer.sendMessage(destination,text); } return "send over"; } }
四、结果
作者:null-npe 出处:https://www.cnblogs.com/npe 由于作者个人水平有限,如果文中有什么错误,欢迎指出。以免更多的人被误导。 |