SpringBoot整合ActiveMQ
一、准备工作
1.准备工具 从ActiveMQ官方上下载ActiveMQ服务
下载地址:http://activemq.apache.org/download.html
我当前下载的是版本是5.15.9 官方备注:当前最新的稳定版本。
下载下来解压后进到window相对应的版本的bin目录下双击activemq.bat
如上图所示说明ActiveMQ服务器启动成功了
二、开始创建
2.1、打开eclipse或者idea新建两个Maven项目一个作为生产者一个作为消费者 之后在两个项目的pom.xml中添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> <!-- json处理依赖 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.6</version> </dependency>
2.2、在resources文件下面新建一个application.properties文件 配置如下:
spring.activemq.broker-url=tcp://127.0.0.1:61616 user: admin password: admin queue: elegant
2.3、创建QueueConfig(当前类主要是在activemq创建队列)
import org.apache.activemq.command.ActiveMQQueue; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.jms.Queue; /** * Created by hezhipeng on 2019/4/16. */ @Configuration public class Queueconfig { @Value("${queue}") private String queue; @Bean public Queue logQueue(){ return new ActiveMQQueue(queue); } }
2.4 创建实体类
public class User { private Long id; private String name; private String age; public User(Long id, String name, String age) { this.id = id; this.name = name; this.age = age; }
2.5、创建生产者类Producer
import javax.jms.Queue; import java.util.UUID; @Component @EnableScheduling public class Producer { @Autowired private JmsMessagingTemplate factor; @Autowired private Queue queue; private int age =18; //每5秒钟执行一次 @Scheduled(fixedRate = 5000) public void send(){ age++; User user = new User(System.currentTimeMillis(), UUID.randomUUID().toString(),age+""); String json = JSONObject.toJSONString(user); System.out.println("生产者正式生产数据啦:"+json); factor.convertAndSend(queue,json); } }
2.6 启动项目 生产者已经弄好了 如下图:
三、创建消费者
3.1、在pom.xml添加依赖和生产者一致就OK啦
3.2.新建 application.properties
spring.activemq.broker-url=tcp://127.0.0.1:61616 user: admin password: admin queue: elegant
3.3、创建Consumer类
@Component public class Consumer { @JmsListener(destination = "${queue}") public void receiver(String msg){ System.out.println("消费者开始读取数据啦:"+msg); } }
3.4 启动项目 如下图说明消费者开始消费了