SpringBoot 简单集成ActiveMQ
ActiveMQ安装配置步骤见:https://www.cnblogs.com/vincenshen/p/10635362.html
第一步,pom.xml引入ActiveMQ依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
第二步,application.properties中配置activemq
spring.activemq.broker-url=tcp://172.16.65.243:61616 spring.activemq.in-memory=true spring.activemq.pool.enabled=false spring.activemq.user=admin spring.activemq.password=admin
第三步,Producer类编写
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class Producer { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Scheduled(fixedRate = 2000) // 使用定时任务,每两秒向mq中发送一个消息 public void sendMsg(){ Map<String, String> ptpMap = new HashMap<>(); ptpMap.put("hello", "activeMQ"); jmsMessagingTemplate.convertAndSend("ptp", ptpMap); } }
第四步,Consumer编写
import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; import java.util.Map; @Component public class Consumer { @JmsListener(destination = "ptp") // 通过JmsListerner实时获取mq中的消息 public void readMsg(Map map){ System.out.println("currentTimeMillis" + System.currentTimeMillis() + "::ptp = [" + map + "]"); } }
第五步,测试效果
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.3.RELEASE) 2019-04-01 14:37:30.686 INFO 71766 --- [ main] c.v.v.VcenterEventApplication : Starting VcenterEventApplication on shongbing-a01.vmware.com with PID 71766 (/Users/shongbing/Downloads/vcenter_event/target/classes started by shongbing in /Users/shongbing/Downloads/vcenter_event) 2019-04-01 14:37:30.689 INFO 71766 --- [ main] c.v.v.VcenterEventApplication : No active profile set, falling back to default profiles: default 2019-04-01 14:37:31.564 INFO 71766 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler' 2019-04-01 14:37:31.755 INFO 71766 --- [ main] c.v.v.VcenterEventApplication : Started VcenterEventApplication in 1.422 seconds (JVM running for 2.162) currentTimeMillis1554100651824::ptp = [{hello=activeMQ}] currentTimeMillis1554100651828::ptp = [{hello=activeMQ}] currentTimeMillis1554100653755::ptp = [{hello=activeMQ}] currentTimeMillis1554100655755::ptp = [{hello=activeMQ}] currentTimeMillis1554100657755::ptp = [{hello=activeMQ}] currentTimeMillis1554100659757::ptp = [{hello=activeMQ}]