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(高级消息队列协议)的消息中 ...
随机推荐
- Wannafly挑战赛27 C蓝魔法师
链接Wannafly挑战赛27 C蓝魔法师 给出一棵树,求有多少种删边方案,使得删后的图每个连通块大小小于等于\(k\),\(n,k\leq 2*10^3\) 假设我们正在考虑\(i\)这个子树,那么 ...
- thinkphp 项目不能直接域名访问 而要加index.php 才能访问
一.apache 服务器配置问题 vim /usr/local/apache2/conf/httpd.conf 在ifModule这里加入index.php <IfModule dir_modu ...
- [原创] Delphi Win API函数 操作帮助文件 HtmlHelpA函数介绍
Delphi Win API函数 操作帮助文件 HtmlHelpA函数介绍 函数原型:HWND HtmlHelpA( HWND hwndCaller, LPCSTR pszFile, UINT uCo ...
- Check the port occupy on Mac OSX
Check the port occupy on Mac OSX lsof -i :7070 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME si ...
- Linux系统下安装jenkins使用
jenkins 2.190.1 yum 安装 devops一梦千年 发布时间:10-0916:28 jenkins 2.190.1 yum 安装记录 安装环境: 所需安装包: https://pkg. ...
- linux运维、架构之路-HTTP服务
一.HTTP协议 1.介绍 HTTP协议,全称HyperText Transfer Protocol,中文名为超文本传输协议,是互联网中最常用的一种网络协议.HTTP协议是互联网上常用的通信协议之一. ...
- TextView控件常用属性
常用属性 android:id——控件ID android:layout_width——控件宽度 android:layout_height——控件高度 android:text——文本内容 andr ...
- web应用,http协议简介,web框架
一.web应用 web应用程序是一种可以通过Web访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要再安装其他软件.应用程序有两种模式C/S.B/S.C/S是客户端 ...
- 树状数组(一维&二维函数)
//一维 void add(int x,int p) { while(x<=n)t[x]+=p,x+=(x&(-x)); } int query(int x) { int ans=0; ...
- [NOI2014] 魔法森林 (二分答案,并查集)
本思路仅供参考,数据强一点应该该会被卡. 本蒟蒻没有打 \(link\) - \(cut\) - \(tree\) . 而是用暴力水了过去. 具体思路很简单,先二分最少的 \(a_i\) , 再在 \ ...