SpringBoot集成ActiveMq消息队列实现即时和延迟处理
原文链接:https://blog.csdn.net/My_harbor/article/details/81328727
一、安装ActiveMq
具体安装步骤:自己谷歌去
二、新建springboot项目
具体步骤:自己谷歌去
三、项目结构
四、引入activemq
<!-- activeMq消息队列 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
五、编写消息数据模型
1、JMS定义了五种不同的消息格式,可以根据实际情况选则使用,本例子使用的是ObjectMessage(序列化的Java对象)
StreamMessage -- Java原始值的数据流
· MapMessage--一套名称-值对
· TextMessage--一个字符串对象
· ObjectMessage--一个序列化的 Java对象
· BytesMessage--一个未解释字节的数据流
2、编写的消息对象需要实现序列化接口,代码如下:
package com.sky.frame.activemq;
import cn.hutool.core.date.DateUtil;
import lombok.*;
import java.io.Serializable;
import java.util.Date;
/**
* 消息模型
* 消息可以是任意数据类型
*/
@Getter
@Setter
@Builder
public class MessageModel implements Serializable {
private String titile;
private String message;
@Override
public String toString() {
return "MessageModel{" +
"titile='" + titile + '\'' +
", message='" + message + '\'' +
", date=" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") +
'}';
}
}
六、编写配置类
从ActiveMQ5.12.2开始,为了增强安全行,ActiveMQ强制用户配置可序列化的包名,否则报错
package com.sky.frame.activemq.config;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @modified By
* @description 从ActiveMQ5.12.2 开始,为了增强这个框架的安全性,ActiveMQ将强制用户配置可序列化的包名
* @date Created in 2018/7/31 19:09
*/
@Component
public class ActiveMqConfig {
@Bean
public ActiveMQConnectionFactory factory(@Value("${spring.activemq.broker-url}") String url){
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
// 设置信任序列化包集合
List<String> models = new ArrayList<>();
models.add("java.lang");
models.add("java.util");
models.add("com.sky.frame.activemq");
factory.setTrustedPackages(models);
// 设置处理机制
RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
redeliveryPolicy.setMaximumRedeliveries(0); // 消息处理失败重新处理次数
factory.setRedeliveryPolicy(redeliveryPolicy);
return factory;
}
}
七、编写生产者
生产者提供两个发送消息的方法,一个是即时发送消息,一个是延时发送消息。延时发送消息需要手动修改activemq目录conf下的activemq.xml配置文件,开启延时,设置schedulerSupport="true",然后重启activemq即可
可以在生产者里事先定义好消息队列,我在这里定义好了一个default.queue队列,用于一会测试
package com.sky.frame.activemq;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import javax.jms.*;
import java.io.Serializable;
/**
* 消息生产者
*/
@Service("acProducer")
public class Producer {
public static final Destination DEFAULT_QUEUE = new ActiveMQQueue("default.queue");
@Autowired
private JmsMessagingTemplate template;
/**
* 发送消息
* @param destination destination是发送到的队列
* @param message message是待发送的消息
*/
public <T extends Serializable> void send(Destination destination, T message){
template.convertAndSend(destination, message);
}
/**
* 延时发送
* @param destination 发送的队列
* @param data 发送的消息
* @param time 延迟时间
*/
public <T extends Serializable> void delaySend(Destination destination, T data, Long time){
Connection connection = null;
Session session = null;
MessageProducer producer = null;
// 获取连接工厂
ConnectionFactory connectionFactory = template.getConnectionFactory();
try {
// 获取连接
connection = connectionFactory.createConnection();
connection.start();
// 获取session,true开启事务,false关闭事务
session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建一个消息队列
producer = session.createProducer(destination);
producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());
ObjectMessage message = session.createObjectMessage(data);
//设置延迟时间
message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
// 发送消息
producer.send(message);
session.commit();
} catch (Exception e){
e.printStackTrace();
} finally {
try {
if (producer != null){
producer.close();
}
if (session != null){
session.close();
}
if (connection != null){
connection.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
}
八、编写消费者,监听default.queue这个消息队列
package com.sky.frame.activemq;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
/**
* 消费者
*/
@Component
public class Consumer {
@JmsListener(destination = "default.queue")
public void receiveQueue(MessageModel message){
System.out.println("收到消息"+message.toString());
}
}
九、yml配置文件
好了,到这里springboot整合activeMQ完成了,接下来我们来测试下,测试的消息往之前定义好的default.queue队列发送,
代码入下:
import com.sky.SkyApplication;
import com.sky.frame.activemq.MessageModel;
import com.sky.frame.activemq.Producer;
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 java.util.Date;
/**
* @modified By
* @description
* @date Created in 2018/7/31 17:19
*/
@SpringBootTest(classes = SkyApplication.class)
@RunWith(SpringRunner.class)
public class ActiveMqTest {
/**
* 消息生产者
*/
@Autowired
private Producer producer;
/**
* 及时消息队列测试
*/
@Test
public void test(){
MessageModel messageModel = MessageModel.builder()
.message("测试消息")
.titile("消息000")
.build();
// 发送消息
producer.send(Producer.DEFAULT_QUEUE, messageModel);
}
/**
* 延时消息队列测试
*/
@Test
public void test2(){
for (int i=0;i< 20;i++){
MessageModel messageModel = MessageModel.builder()
.titile("延迟10秒执行")
.message("测试消息" + i)
.build();
// 发送延迟消息
producer.delaySend(Producer.DEFAULT_QUEUE, messageModel, 10000L);
}
try {
// 休眠100秒,等等消息执行
Thread.currentThread().sleep(100000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
及时发送的效果如下:
延迟发送效果如下:
SpringBoot集成ActiveMq消息队列实现即时和延迟处理的更多相关文章
- SpringBoot集成RabbitMQ消息队列搭建与ACK消息确认入门
1.RabbitMQ介绍 RabbitMQ是实现AMQP(高级消息队列协议)的消息中间件的一种,最初起源于金融系统,用于在分布式系统中存储转发消息,在易用性.扩展性.高可用性等方面表现不俗.Rabbi ...
- springboot中activeMQ消息队列的引入与使用(发送短信)
1.引入pom依赖 <!--activemq--><dependency> <groupId>org.springframework.boot</groupI ...
- SpringBoot配置activemq消息队列
1.配置pom相关依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...
- ActiveMQ基础教程(四):.net core集成使用ActiveMQ消息队列
接上一篇:ActiveMQ基础教程(三):C#连接使用ActiveMQ消息队列 这里继续说下.net core集成使用ActiveMQ.因为代码比较多,所以放到gitee上:https://gitee ...
- SpringBoot集成ActiveMQ
前面提到了原生API访问ActiveMQ和Spring集成ActiveMQ.今天讲一下SpringBoot集成ActiveMQ.SpringBoot就是为了解决我们的Maven配置烦恼而生,因此使用S ...
- activemq消息队列的使用及应用docker部署常见问题及注意事项
activemq消息队列的使用及应用docker部署常见问题及注意事项 docker用https://hub.docker.com/r/rmohr/activemq/配置在/data/docker/a ...
- JAVA的设计模式之观察者模式----结合ActiveMQ消息队列说明
1----------------------观察者模式------------------------------ 观察者模式:定义对象间一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的 ...
- ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息
Java消息服务(Java Message Service ,JMS)是一个Java标准,定义了使用消息代理的通用API .在JMS出现之前,每个消息代理都有私有的API,这就使得不同代理之间的消息代 ...
- C#实现ActiveMQ消息队列
本文使用C#实现ActiveMQ消息队列功能. 一.首先需要导入两个包,分别是:Apache.NMS 和 Apache.NMS.ActiveMQ 二.创建Winform程序实现生产者功能. 三.Pro ...
随机推荐
- 洛谷P2312解方程题解
题目 暴力能得\(30\),正解需要其他的算法操作,算法操作就是用秦九韶算法来优化. 秦九韶算法就是求多项式的值时,首先计算最内层括号内一次多项式的值,然后由内向外逐层计算一次多项式的值,然后就将求\ ...
- Hadoop NameNode 元数据以及查看元数据的方式
HDFS中NameNode工作机制1.NameNode的主要功能(1)负责客户端请求的响应: (2)负责元数据的管理. 2.元数据管理namenode对数据管理采用了三种存储形式: (1)内存元数据: ...
- 以前进行的程序安装创建了挂起的文件操作(SqlServer2000或SqlServer 2000 SP4补丁安装)
在安装SqlServer 2000或者SqlServer 2000 SP4补丁时常常会出现这样的提示,从而不能进行安装,即使重新启动了计算机,也还是会有同样的提示.在网上查了一下资料,原来是注册表里记 ...
- Python多线程与多进程详解
进程,线程,协程https://blog.csdn.net/qq_23926575/article/details/76375337 多进程 https://www.cnblogs.com/lipij ...
- Mysql sql_mode设置 timestamp default 0000-00-00 00:00:00 创建表失败处理
往数据库里创建新表的时候报错: [Err] 1067 - Invalid default value for 'updateTime' DROP TABLE IF EXISTS `passwd_res ...
- python,在路径中引用变量的方法
fr = open('E:\\pyCharm\\LogisticRegression\\1\\'+变量+'.txt')
- fork 可能导致subprocess崩溃
https://docs.python.org/zh-cn/3/library/multiprocessing.html 在 3.8 版更改: 对于 macOS,spawn 启动方式是默认方式. 因为 ...
- Windows上安装nodejs版本管理器nvm 安装成功之后重启终端失效
nvm 安装成功之后重启终端失效(command not found) 安装nvm之后node不可用,“node”不是内部或外部命令,也不是可运行的程序或批处理文件(ng) 安装nvm: 下载nvm压 ...
- python监控rabbitmq的消息队列数量
[root@localhost chen]# cat b.py #!/usr/bin/python # -*- coding: UTF-8 -*- import json,time import re ...
- openresty开发系列25--openresty中使用json模块
openresty开发系列25--openresty中使用json模块 web开发过程中,经常用的数据结构为json,openresty中封装了json模块,我们看如何使用 一)如何引入cjson模块 ...