rabbitMQ实现推迟队列
一. 使用原生Api
1.RabbitMQ 相关
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.0</version>
</dependency>
class RabbitMqContex {
private static final String host = "127.0.0.1";
private static final int port = 5672;
public static ConnectionFactory getFactory() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
factory.setPort(port);
factory.setUsername("guest");
factory.setPassword("guest");
return factory;
}
public static Connection getFactoryConnection() throws IOException, TimeoutException {
return getFactory().newConnection();
}
public static Channel getChannel() throws IOException, TimeoutException {
return getFactoryConnection().createChannel();
}
}
class DelayProducer {
public static void publish(String exchange, String content, int delayMillseconds) throws Exception {
Channel channel = null;
String delayExchangeName = exchange + "_delay";
String delayQueueName = delayExchangeName + "->queue_delay";
String delayRouteKey = "dead";
//设置死信队列参数
Map<String, Object> arguments = new HashMap<>();
arguments.put("x-dead-letter-exchange", exchange);
try {
channel = RabbitMqContex.getChannel();
channel.exchangeDeclare(exchange, "fanout", true, false, null);
channel.exchangeDeclare(delayExchangeName, "direct", true, false, null);
channel.queueDeclare(delayQueueName, true, false, false, arguments);
channel.queueBind(delayQueueName, delayExchangeName, delayRouteKey);
//设计消息超时参数
AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
AMQP.BasicProperties properties = builder.expiration(Integer.toString(delayMillseconds)).build();
channel.basicPublish(delayExchangeName, delayRouteKey, properties, content.getBytes());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (null != channel) {
try {
channel.close();
} catch (Exception ex) {
}
}
}
}
}
2.调用如下
public static void main(String[] args) throws Exception {
DelayProducer.publish("rewardSuccess", "{\"customerId\":123032}", 60 * 1000);
}
二使用spring的 RabbitTemplate 和 RabbitAdmin
1.注入bean
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; /**
* 系统配置
*
* @author
* @date 2017/10/19
*/
@Configuration
public class RabbitMqConfig { @Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.port}")
private int port;
@Value("${spring.rabbitmq.username:guest}")
private String username;
@Value("${spring.rabbitmq.password:guest}")
private String password; @Bean(name = "rabbitMq.connectionFactory")
public ConnectionFactory getConnectionFactory() {
CachingConnectionFactory factory = new CachingConnectionFactory();
factory.setHost(host);
factory.setPort(port);
factory.setUsername(username);
factory.setPassword(password);
return factory;
} @Bean
public RabbitTemplate getRabbitTemplate(
@Qualifier("rabbitMq.connectionFactory") ConnectionFactory connectionFactory) {
return new RabbitTemplate(connectionFactory);
} @Bean
public RabbitAdmin getRabbitAdmin(
@Qualifier("rabbitMq.connectionFactory") ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
} @Bean
public MessageProperties getRabbitTemplateMessageProperties() {
MessageProperties messageProperties = new MessageProperties();
messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
messageProperties.setHeader("content_encoding", "JSON");
return messageProperties;
}
}
2.发送工具类
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j; /**
* 功能描述:
*
* @version 1.0
* @author:
* @createDate: 2017/10/19
*/
@Configuration
@Slf4j
public class RabbitMqSender {
/**
* rabbitTemplate
*/
@Autowired
private RabbitTemplate rabbitTemplate; /**
* rabbitAdmin
*/
@Autowired
private RabbitAdmin rabbitAdmin; /**
* messageProperties
*/
@Autowired
private MessageProperties messageProperties; /**
* init
*/
@PostConstruct
public void init() {
} private void declareExchange(String exchange) {
rabbitAdmin.declareExchange(new FanoutExchange(exchange, true, false, null));
} private MessageProperties getMessageProperties(Map<String, String> header) {
if (header == null) {
return this.messageProperties;
} MessageProperties customMessageProperties = new MessageProperties();
customMessageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
customMessageProperties.setHeader("content_encoding", "JSON");
for (Map.Entry<String, String> item : header.entrySet()) {
customMessageProperties.setHeader(item.getKey(), item.getValue());
}
return customMessageProperties;
} /**
* sendMessage
*/
public void publish(String exchange, String content) {
publish(exchange, content, (Map) null);
} /**
* sendMessage
*/
public void publish(String exchange, String content, Map<String, String> properties) {
publish(exchange, content, getMessageProperties(properties));
} /**
* sendMessage
*/
private void publish(String exchange, String content, MessageProperties messageProperties) {
declareExchange(exchange);
Message message = new Message(content.getBytes(StandardCharsets.UTF_8), messageProperties);
try {
rabbitTemplate.send(exchange, "", message);
log.debug("推送给exchange:{},消息体:{} 成功", exchange, content);
} catch (Exception e) {
log.error("推送给exchange:{},消息体:{} 失败!!", exchange, content, e);
throw e;
}
} public void delayPublish(String exchange, String content, int millseconds) {
String delayExchangeName = exchange + "_delay";
String delayQueueName = delayExchangeName + "->queue_delay";
String delayRouteKey = "dead";
Map<String, Object> arguments = new HashMap<>();
arguments.putIfAbsent("x-dead-letter-exchange", exchange);
declareExchange(exchange);
declareExchange(delayExchangeName);
rabbitAdmin.declareQueue(new Queue(delayQueueName, true, false, false, arguments));
rabbitAdmin.declareBinding(new Binding(delayQueueName, Binding.DestinationType.QUEUE, delayExchangeName,
delayRouteKey, Collections.emptyMap()));
MessageProperties messageProperties = getMessageProperties(Collections.emptyMap());
messageProperties.setExpiration(Integer.toString(millseconds));
publish(delayExchangeName, content, messageProperties);
}
}
rabbitMQ实现推迟队列的更多相关文章
- 如何基于RabbitMQ实现优先级队列
概述 由于种种原因,RabbitMQ到目前为止,官方还没有实现优先级队列,只实现了Consumer的优先级处理. 但是,迫于种种原因,应用层面上又需要优先级队列,因此需求来了:如何为RabbitMQ加 ...
- rabbitmq批量删除队列
有些时候,我们需要批量的删除rabbitmq中的队列,尤其是对于那些客户端配置了队列不存在时自动创建,但断开时不自动删除的应用来说. rabbitmqctl并没有包含直接管理队列的功能,其提供的vho ...
- RabbitMQ分布式消息队列服务器(一、Windows下安装和部署)
RabbitMQ消息队列服务器在Windows下的安装和部署-> 一.Erlang语言环境的搭建 RabbitMQ开源消息队列服务是使用Erlang语言开发的,因此我们要使用他就必须先进行Erl ...
- rabbitmq学习(二):rabbitmq(消息队列)的作用以及rabbitmq之直连交换机
前言 上篇介绍了AMQP的基本概念,组成及其与rabbitmq的关系.了解了这些东西后,下面我们开始学习rabbitmq(消息队列)的作用以及用java代码和rabbitmq通讯进行消息发布和接收.因 ...
- .NET 环境中使用RabbitMQ RabbitMQ与Redis队列对比 RabbitMQ入门与使用篇
.NET 环境中使用RabbitMQ 在企业应用系统领域,会面对不同系统之间的通信.集成与整合,尤其当面临异构系统时,这种分布式的调用与通信变得越发重要.其次,系统中一般会有很多对实时性要求不高的 ...
- 基于rabbitMQ 消息延时队列方案 模拟电商超时未支付订单处理场景
前言 传统处理超时订单 采取定时任务轮训数据库订单,并且批量处理.其弊端也是显而易见的:对服务器.数据库性会有很大的要求,并且当处理大量订单起来会很力不从心,而且实时性也不是特别好 当然传统的手法还可 ...
- C#调用RabbitMQ实现消息队列
前言 我在刚接触使用中间件的时候,发现,中间件的使用并不是最难的,反而是中间件的下载,安装,配置才是最难的. 所以,这篇文章我们从头开始学习RabbitMq,真正的从头开始. 关于消息队列 其实消息队 ...
- 干货!基于SpringBoot的RabbitMQ多种模式队列实战
目录 环境准备 安装RabbitMQ 依赖 连接配置 五种队列模式实现 1 点对点的队列 2 工作队列模式Work Queue 3 路由模式Routing 4 发布/订阅模式Publish/Subsc ...
- RabbitMQ与Redis队列对比
本文仅针对RabbitMQ与Redis做队列应用时的情况进行对比具体采用什么方式实现,还需要取决于系统的实际需求 简要介绍 RabbitMQ RabbitMQ是实现AMQP(高级消息队列协议)的消息中 ...
随机推荐
- Mybatis学习笔记大纲
Mybatis学习笔记大纲: 一.MyBatis简介 二.MyBatis-HelloWorld 三.MyBatis-全局配置文件 四.MyBatis-映射文件 五.MyBatis-动态SQL 六.My ...
- wannafly25 E 01串
链接 wannafly25 E 01串 给出一个\(01\)串,有两种操作,操作一是将某一个位置的数字修改,操作二是询问某一个区间,将这个区间看做\(1\)个二进制数,可以随意加减\(2\)的幂次,问 ...
- Pycharn破解补丁激活
Pycharn破解补丁激活 到期时间: 1. 下载 https://pan.baidu.com/s/1mcQM8CLUnweY02ahKEr4PQ 并将 JetbrainsCrack-release ...
- selenium 自动化的坑(2)
UI自动化,一天一坑系列(2) 今天要介绍的坑是这样的:在使用google浏览器的过程中,F12查看页面元素,我的操作步骤是先F12,然后点击箭头,接着点击要查找的元素来实现元素查看,不知道你是不是这 ...
- leetcode-167周赛-1292-元素和小于等于阈值的正方形的最大边长
题目描述; 自己的提交:超时 class Solution: def maxSideLength(self, mat: List[List[int]], threshold: int) -> i ...
- python-Exception异常使用
Exception #自定义异常类 ,MyInputExcp继承Exception异常 class MyInputExcp(Exception): def __init__(self, lenght, ...
- 英语单词composing
composing 来源——书籍Python.Crash.Course.2015.11 Using Individual Values from a List You can use individu ...
- c#类的定义,c#中的关健字,C#标识符
什么是类:一种数数据结构,存储数据成员,方法成员,和其它的内容,便 于方便 谳用C#语法: class 类名{ //TODO} C#中关键字(小写)不能作为方法名,类名,命名空间名等, static ...
- [USACO17FEB]Why Did the Cow Cross the Road III G (树状数组,排序)
题目链接 Solution 二维偏序问题. 现将所有点按照左端点排序,如此以来从左至右便满足了 \(a_i<a_j\) . 接下来对于任意一个点 \(j\) ,其之前的所有节点都满足 \(a_i ...
- 『转』一千行MySQL学习笔记
/* 启动MySQL */ net start mysql /* 连接与断开服务器 */ mysql -h 地址 -P 端口 -u 用户名 -p 密码 /* 跳过权限验证登录MySQL */ mysq ...