代码参考地址:https://github.com/zhaofengdeng/springboot-demo.git
分支:feature-activeMQ
第一步安装activeMQ
- 下载activeMQ我使用的是5.15.9版本
- 安装前确保已经有jdk,并且jdk的版本要满足ActiveMQ的要求
- 进入到apache-activemq-5.15.9\bin\win32或者win64
- 双击activemq.bat
- 启动标志
- 打开浏览器,输入http://localhost:8161/admin/ ,弹出一个windows安全提示框,提示输入activemq的用户名和密码
- apache-activemq-5.15.9\conf这个目录,找到jetty-realm.properties文件
- 打开该文件,找到文件的末尾,格式是 用户名: 密码,用户角色 ,如下图所示:
- 登录成功以后,就可以看到activemq的主页了
第二步:spirngBoot使用activeMQ,简单使用
第一步:引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
第二步:application.properties
#activemq
#http://localhost:8161(管理端口)
#tcp://127.0.0.1:61616(服务端口)
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
# 如果此处设置为true,需要加activemq-pool的依赖包,否则会自动配置失败,报JmsMessagingTemplate注入失败
#spring.activemq.pool.enabled=false时,每发送一条数据创建一个连接
spring.activemq.pool.enabled=true
#连接池最大连接数
spring.activemq.pool.max-connections=5
#空闲的连接过期时间,默认为30秒
spring.activemq.pool.idle-timeout=30000
#强制的连接过期时间,与idleTimeout的区别在于:idleTimeout是在连接空闲一段时间失效,而expiryTimeout不管当前连接的情况,只要达到指定时间就失效。默认为0,never
spring.activemq.pool.expiry-timeout=0
第三步:消息发送与消息接收
@RestController
@RequestMapping(value = "/active_mq/producer")
public class ActiveMQProducerController {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
public String sendMsg(HttpServletRequest request) {
System.out.println(jmsMessagingTemplate);
jmsMessagingTemplate.convertAndSend("my_msg", request.getParameter("msg"));
return "msg发送成功";
}
@RequestMapping("/send_map")
public String sendMap() {
Map map = new HashMap();
map.put("mobile", "13888888888");
map.put("content", "王总喜提兰博基尼");
jmsMessagingTemplate.convertAndSend("my_map", map);
return "map发送成功";
}
}
@Component
public class ActiveMQConsumer {
@JmsListener(destination = "my_msg")
public void readMsg(String text) {
System.out.println("接收到消息:" + text);
}
@JmsListener(destination = "my_map")
public void readMap(Map map) {
System.out.println(map);
}
}