一、安装activeMQ

​ 安装步骤参照网上教程,本文不做介绍

二、修改activeMQ配置文件

​ broker新增配置信息 schedulerSupport="true"

<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}" schedulerSupport="true" >

        <destinationPolicy>
<policyMap>
<policyEntries>
<policyEntry topic=">" >
<!-- The constantPendingMessageLimitStrategy is used to prevent
slow topic consumers to block producers and affect other consumers
by limiting the number of messages that are retained
For more information, see: http://activemq.apache.org/slow-consumer-handling.html -->
<pendingMessageLimitStrategy>
<constantPendingMessageLimitStrategy limit="1000"/>
</pendingMessageLimitStrategy>
</policyEntry>
</policyEntries>
</policyMap>
</destinationPolicy>

三、创建SpringBoot工程

  1. 配置ActiveMQ工厂信息,信任包必须配置否则会报错
package com.example.demoactivemq.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.context.annotation.Configuration; import java.util.ArrayList;
import java.util.List; /**
* @author shanks on 2019-11-12
*/
@Configuration
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("com.example.demoactivemq.domain");
factory.setTrustedPackages(models); return factory;
} }
  1. 消息实体类
package com.example.demoactivemq.domain;

import lombok.Builder;
import lombok.Data; import java.io.Serializable; /**
* @author shanks on 2019-11-12
*/ @Builder
@Data
public class MessageModel implements Serializable {
private String titile;
private String message;
}
  1. 生产者
package com.example.demoactivemq.producer;

import lombok.extern.slf4j.Slf4j;
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; /**
* 消息生产者
*
* @author shanks
*/
@Service
@Slf4j
public class Producer { public static final Destination DEFAULT_QUEUE = new ActiveMQQueue("delay.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);
log.info("发送消息:{}", data);
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();
}
}
}
}
  1. 消费者
package com.example.demoactivemq.producer;

import com.example.demoactivemq.domain.MessageModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component; /**
* 消费者
*/
@Component
@Slf4j
public class Consumer { @JmsListener(destination = "delay.queue")
public void receiveQueue(MessageModel message) {
log.info("收到消息:{}", message);
}
}
  1. application.yml
spring:
activemq:
broker-url: tcp://localhost:61616
  1. 测试类
package com.example.demoactivemq;

import com.example.demoactivemq.domain.MessageModel;
import com.example.demoactivemq.producer.Producer;
import org.junit.jupiter.api.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; @SpringBootTest(classes = DemoActivemqApplication.class)
@RunWith(SpringRunner.class)
class DemoActivemqApplicationTests { /**
* 消息生产者
*/
@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 < 5; 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();
}
} }

执行结果

2019-11-12 22:18:52.939  INFO 17263 --- [           main] c.e.demoactivemq.producer.Producer       : 发送消息:MessageModel(titile=延迟10秒执行, message=测试消息0)
2019-11-12 22:18:52.953 INFO 17263 --- [ main] c.e.demoactivemq.producer.Producer : 发送消息:MessageModel(titile=延迟10秒执行, message=测试消息1)
2019-11-12 22:18:52.958 INFO 17263 --- [ main] c.e.demoactivemq.producer.Producer : 发送消息:MessageModel(titile=延迟10秒执行, message=测试消息2)
2019-11-12 22:18:52.964 INFO 17263 --- [ main] c.e.demoactivemq.producer.Producer : 发送消息:MessageModel(titile=延迟10秒执行, message=测试消息3)
2019-11-12 22:18:52.970 INFO 17263 --- [ main] c.e.demoactivemq.producer.Producer : 发送消息:MessageModel(titile=延迟10秒执行, message=测试消息4)
2019-11-12 22:19:03.012 INFO 17263 --- [enerContainer-1] c.e.demoactivemq.producer.Consumer : 收到消息:MessageModel(titile=延迟10秒执行, message=测试消息0)
2019-11-12 22:19:03.017 INFO 17263 --- [enerContainer-1] c.e.demoactivemq.producer.Consumer : 收到消息:MessageModel(titile=延迟10秒执行, message=测试消息1)
2019-11-12 22:19:03.019 INFO 17263 --- [enerContainer-1] c.e.demoactivemq.producer.Consumer : 收到消息:MessageModel(titile=延迟10秒执行, message=测试消息2)
2019-11-12 22:19:03.020 INFO 17263 --- [enerContainer-1] c.e.demoactivemq.producer.Consumer : 收到消息:MessageModel(titile=延迟10秒执行, message=测试消息3)
2019-11-12 22:19:03.021 INFO 17263 --- [enerContainer-1] c.e.demoactivemq.producer.Consumer : 收到消息:MessageModel(titile=延迟10秒执行, message=测试消息4)

比你优秀的人比你还努力,你有什么资格不去奋斗!!!

SpringBoot之ActiveMQ实现延迟消息的更多相关文章

  1. SpringBoot - 集成RocketMQ实现延迟消息队列

    目录 前言 环境 具体实现 前言 RocketMQ是阿里巴巴在2012年开源的分布式消息中间件,记录下SpringBoot整合RocketMQ的方式,RocketMQ的安装可以查看:Windows下安 ...

  2. ActiveMQ延迟消息配置

    ActiveMQ使用延迟消息,需要在activemq.xml配置文件中添加这项: schedulerSupport="true" <broker xmlns="ht ...

  3. SpringBoot集成ActiveMq消息队列实现即时和延迟处理

    原文链接:https://blog.csdn.net/My_harbor/article/details/81328727 一.安装ActiveMq 具体安装步骤:自己谷歌去 二.新建springbo ...

  4. SpringBoot系列八:SpringBoot整合消息服务(SpringBoot 整合 ActiveMQ、SpringBoot 整合 RabbitMQ、SpringBoot 整合 Kafka)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合消息服务 2.具体内容 对于异步消息组件在实际的应用之中会有两类: · JMS:代表作就是 ...

  5. 解决Springboot整合ActiveMQ发送和接收topic消息的问题

    环境搭建 1.创建maven项目(jar) 2.pom.xml添加依赖 <parent> <groupId>org.springframework.boot</group ...

  6. SpringBoot JMS(ActiveMQ) 使用实践

    ActiveMQ 1. 下载windows办的activeMQ后,在以下目录可以启动: 2. 启动后会有以下提示 3. 所以我们可以通过http://localhost:8161访问管理页面,通过tc ...

  7. Web项目容器集成ActiveMQ & SpringBoot整合ActiveMQ

    集成tomcat就是随项目启动而启动tomcat,最简单的方法就是监听器监听容器创建之后以Broker的方式启动ActiveMQ. 1.web项目中Broker启动的方式进行集成 在这里采用Liste ...

  8. springboot与ActiveMQ整合

    前言 很多项目, 都不是一个系统就做完了. 而是好多个系统, 相互协作来完成功能. 那, 系统与系统之间, 不可能完全独立吧? 如: 在学校所用的管理系统中, 有学生系统, 资产系统, 宿舍系统等等. ...

  9. RabbitMQ延迟消息学习

    准备做一个禁言自动解除的功能,立马想到了订单的超时自动解除,刚好最近在看RabbitMQ的实现,于是想用它实现,查询了相关文档发现确实可以实现,动手编写了这篇短文. 准备工作 1.Erlang安装请参 ...

随机推荐

  1. 设计模式 - 动态代理原理及模仿JDK Proxy 写一个属于自己的动态代理

    本篇文章代码内容较多,讲的可能会有些粗糙,大家可以选择性阅读. 本篇文章的目的是简单的分析动态代理的原理及模仿JDK Proxy手写一个动态代理以及对几种代理做一个总结. 对于代理模式的介绍和讲解,网 ...

  2. Spring5源码解析5-ConfigurationClassPostProcessor (上)

    接上回,我们讲到了refresh()方法中的invokeBeanFactoryPostProcessors(beanFactory)方法主要在执行BeanFactoryPostProcessor和其子 ...

  3. Java8新特性之空指针异常的克星Optional类

    Java8新特性系列我们已经介绍了Stream.Lambda表达式.DateTime日期时间处理,最后以"NullPointerException" 的克星Optional类的讲解 ...

  4. Vue框架构造

    Vue 程序结构框架 Vue.js是典型的MVVM框架,什么是MVVM框架,介绍之前我们先介绍下什么是MVC框架 MVC 即 Model-View-Controller 的缩写,就是 模型-视图-控制 ...

  5. boost::asio::tcp

    同步TCP通信服务端 #include <boost/asio.hpp> #include <iostream> using namespace boost::asio; in ...

  6. [七年技术总结系列][理论篇]-RBAC权限模型由浅入深

    权限部分将分两章介绍,第一章由浅入深介绍权限理论知识及应用,第二章介绍具体实现.后期再讲述中间件的使用时,还会插入一些权限内容,本质上属于中间件的应用. 权限模块是业务系统最常见.最基本的子集.本章假 ...

  7. liunux中的标准输出。以及常用的 2>dev/null 命令的含义

    了解Linux怎样处理输入和输出是非常重要的.一旦我们了解其原理以后,我们就可以正确熟练地使用脚本把内容输出到正确的位置.同样我们也可以更好地理解输入重定向和输出重定向. 首先我们来了解一下linux ...

  8. 百万年薪python之路 -- 函数的动态参数练习

    1.继续整理函数相关知识点. 2.写函数,接收n个数字,求这些参数数字的和.(动态传参) def func(*args,**kwargs): num_sum = 0 num_dic = [] num ...

  9. CheckBox多选

    前台: <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> & ...

  10. volatile关键字使用

    1.volatile 使用场景(多线程情况下): 适合使用在 一写多读 的情况下: 2.volatile 理解分析: 使用 volatile 关键字修饰的变量,值在改变时会直接刷新到 主内存 中,而不 ...