欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot集成ActiveMQ

程序员文章站 2022-04-30 19:45:36
...

Spring Boot 集成ActiveMQ

使用ActiveMQ版本5.14.0,spring Boot版本1.5.9;

1、向pom.xml 文件中添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2、application.yml添加配置

消费者接受queue消息,需要将pub-sub-domain配置为false

spring:
  jms:
    pub-sub-domain: true #false默认不接受topic消息,而是接受队列queue消息
  activemq:
    broker-url: tcp://172.17.1.25:61616
    in-memory: true
    enabled: false

3、生产者producer

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.jms.Destination;

/**
 *
 * 模拟ActiveMQ生产者
 * 发送方式见Test测试类
 * @Author 孙龙
 */
@Service("producer")
public class Producer {

    @Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
    private JmsMessagingTemplate jmsTemplate;

    // 发送消息,destination是发送到的队列,message是待发送的消息
    public void sendMessage(Destination destination, final String message){
        jmsTemplate.convertAndSend(destination, message);
    }

}

4、消费者Consumer

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class CarDataListener {

    /**
     * 接收通过车辆信息
     *
     * @param carDataInfo
     */
    @JmsListener(destination = "activetest")
    public void getPassInfo(String message) {
        log.info("收到的消息是:" + message);
    }
}

5、测试queue和topic

package com.lilian;

import com.lilian.jms.Producer;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.jms.Destination;

@RunWith(SpringRunner.class)
@SpringBootTest
public class CommMQApplicationTests {

    @Autowired
    private Producer producer;

    @Test
    public void contextLoads() {

        Destination destination = new ActiveMQTopic("activetest");
        // Destination destination1 = new ActiveMQQueue("activetest");

        String info = "测试activeMQ Topic消息!";
        // String info1 = "测试activeMQ Queue消息!";

        producer.sendMessage(destination, info);
        // producer.sendMessage(destination1, info1);
    }

}

6、消息可视化

ActiveMQ的服务器地址加上8161端口。例如: localhost:8161

随后我会将自己写的Demo整理出来开源到github上,在这里公开地址,希望能够帮助到你!