The process of integrating ActiveMQ with Spring Boot

  1. Install the ActiveMQ server, (or not, if not, use memory mq)
  2. 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>
  1. Add Application class
@SpringBootApplication
@EnableScheduling //Send messages using scheduled tasks
public class MqTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(MqTestApplication.class, args);
    }
}
  1. Configure application.yml
spring:
  activemq:
    broker-url: tcp://127.0.01:61616
    packages:
      trust-all: true
  1. 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 + "]";
    }

}
  1. 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++));
    }
}
  1. 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

Keywords: Spring github git

Added by dspeer on Sun, 03 May 2020 07:28:24 +0300