- Install the ActiveMQ server, (or not, if not, use memory mq)
- To build a Spring boot project and add dependencies, just add this one
<!-- Add to acitivemq rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
- Add Application class
@SpringBootApplication @EnableScheduling //Send messages using scheduled tasks public class MqTestApplication { public static void main(String[] args) { SpringApplication.run(MqTestApplication.class, args); } }
- Configure application.yml
spring: activemq: broker-url: tcp://127.0.01:61616 packages: trust-all: true
- To build a data Model, the data types that can be sent and consumed are: string, byte array, map < string,? > and serializable object
// If the message sent is an object, the implements Serializable interface is required public class TModel implements Serializable { private static final long serialVersionUID = -921008687184331557L; private int count; public TModel(int count) { this.count = count; } @Override public String toString() { return "TModel [count=" + count + "]"; } }
- Build Producer
@Component public class Producer { // Inject jms template into Producer, through which we can send messages private final JmsTemplate jmsTemplate; private int count = 0; @Autowired public Producer(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } // Here, use the Spring Boot's scheduled task to send messages @Scheduled(fixedRate = 1000) public void create() { // Using convertAndSend to send messages jmsTemplate.convertAndSend("queue1", new TModel(count++)); } }
- Build Consumer
@Component public class Consumer { @JmsListener(destination = "queue1") public void comsume(TModel content) { System.out.println("recive message from queue1 [" + content + "]"); } }
Special note: if our producers and consumers are in different modules, it is better to abstract the data to be consumed into a common Module. The program serializes and deserializes objects through Serializable. You must ensure that the serialVersionUID of the object model of the producer and consumer is consistent.
Project address: https://github.com/ldwqh0/active-mq-spring.git