POOM file
Import the required activemq jar first packet
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> </dependencies>
Producers
application.yml
server: port: 8090 servlet: context-path: /activemqProducer spring: activemq: broker-url: tcp://127.0.0.1:61616 user: 123 password: 123
ActiveMqConfig
package com.example.activemqtest.config; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.jms.Queue; import javax.jms.Topic; @Configuration public class ActiveMQConfig { @Bean public Queue queue(){ return new ActiveMQQueue("queue2"); } @Bean public Topic topic(){ return new ActiveMQTopic("topic2"); } }
Producers arranged to send a message queue or topic, the injection spring
ProducterController
package com.example.activemqtest.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.jms.Queue; import javax.jms.Topic; @RestController public class ProducterController { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Queue queue; @Autowired private Topic topic; @GetMapping("/sendMsgByQueue") public String sendMsgByQueue(String msg){ jmsMessagingTemplate.convertAndSend(queue,msg); return msg; } @GetMapping("/sendMsgByTopic") public String sendMsgByTopic(String msg){ jmsMessagingTemplate.convertAndSend(topic,msg); return msg; } }
consumer
@JmsListener (Where do you want = "Queue2" ) // method returns to a queue3 @SendTo ( "queue3" ) public String the handleMessage (String MSG) { System.out.println ( "received return is:" + MSG); return "returns:" + MSG; }
These are the way consumers receive queue queue2
To receive topic, you need to increase the allocation
server: port: 8091 servlet: context-path: /activemqConsumer spring: activemq: broker-url: tcp://127.0.0.1:61616 user: 123 password: 123 jms: pub-sub-domain: true
@JmsListener (Where do you want = "topic2" ) public void topicConsumer1 (String MSG) { System.out.println ( "consumer is receiving 1:" + MSG); } @JmsListener (Where do you want = "topic2" ) public void topicConsumer2 (String MSG) { System.out.println ( "consumer 2 receives as:" + MSG); }