1. Install activeMq first
Check whether the installation is completed. Enter similar in the browser: http://localhost:8161 /, access. If there is an access interface of activeMq, the installation of activeMq is successful (the precondition is to configure the java environment);
2. Establish springBoot project
The pom file depends on the following:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
The profile information is as follows:
spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin spring.activemq.in-memory=true spring.activemq.pool.enabled=false
3. Create Producer
Using JmsMessagingTemplate to send messages
package com.example.activemq; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.stereotype.Component; import javax.jms.Destination; /** * @author : Ball ball * @description: TODO * @date : Created in 2019/7/14 11:50 * @modified By: * @version: 1.0 */ @Component public class Producer { @Autowired private JmsMessagingTemplate messagingTemplate; // message sending public void sendMessage(Destination destination, String message) { messagingTemplate.convertAndSend(destination, message); } }
4. Create Consumer
Use annotation @ JmsListener(destination = "myTestQueue") for message monitoring
package com.example.activemq; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; /** * @author : Ball ball * @description: TODO * @date : Created in 2019/7/14 11:55 * @modified By: * @version: 1.0 */ @Component public class Consumer { @JmsListener(destination = "myTestQueue") public void receive(String message){ System.out.println(message); } }
5. controller test
Note: Destination mqQueue = new ActiveMQQueue("myTestQueue");
When listening, the destination should be the same as that at this time.
package com.example.activemq; import org.apache.activemq.command.ActiveMQQueue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.jms.Destination; /** * @author : Ball ball * @description: TODO * @date : Created in 2019/7/14 11:56 * @modified By: * @version: 1.0 */ @Controller public class TestController { @Autowired private Producer producer; @RequestMapping("/send") @ResponseBody public String sendMessage(){ Destination mqQueue = new ActiveMQQueue("myTestQueue"); for (int i = 0; i < 4; i++) { producer.sendMessage(mqQueue,"hello"+i); } return "success"; } }