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(高级消息队列协议)的消息中 ...
随机推荐
- mybaties数据源配置类型(POOLED、JNDI、UNPOOLED)
dataSource的类型可以配置成其内置类型之一,如UNPOOLED.POOLED.JNDI. 如果将类型设置成UNPOOLED,mybaties会为每一个数据库操作创建一个新的连接,并关闭它.该方 ...
- 【leetcode】449. Serialize and Deserialize BST
题目如下: Serialization is the process of converting a data structure or object into a sequence of bits ...
- [super class]和[self class]
参考: https://www.jianshu.com/p/3f2bcc588b44?utm_campaign=hugo&utm_medium=reader_share&utm_con ...
- Android之SAX解析笔记
books.xml: <?xml version="1.0" encoding="utf-8"?> <books> <book i ...
- FastDFS整合普通Maven项目(四)
1.下载官方的源代码:https://codeload.github.com/happyfish100/fastdfs-client-java/zip/master 2.采用maven命令编译成jar ...
- nginx: [emerg] open() "/var/run/nginx/nginx.pid" failed (2: No such file or directory)
测试服务器 问题描述 [root@g-s-- nginx]# /usr/sbin/nginx -c /etc/nginx/nginx.conf open() : No such file or dir ...
- 2A3T我的PMP备考及考试心得20181208
2018年的下半年由于工作不是很忙,所以生活中有更好的精力去做些自己的事情.出于工作需要,我决定考个证书充实下自己,在各大网站搜索解惑后决定考PMP,并报了个培训班 一.PMP考试简介 共200道选择 ...
- 【HDOJ6656】Kejin Player(期望DP)
题意:玩一个共有n级的游戏,i级出发每次可以花a[i]的代价,有p[i]的几率变成i+1级,有1-p[i]的几率变成x[i]级,x[i]<=i 多次询问,每次询问从l级升到r级的期望总代价 n, ...
- Solr核心(内核)
Solr核心(内核) Solr核心(Core)是Lucene索引的运行实例,包含使用它所需的所有Solr配置文件.我们需要创建一个Solr Core来执行索引和分析等操作. Solr应用程序可以包 ...
- linux之rpm软件包管理
1.RPM包的命名规则 例如:httpd-2.2.15-15.el6.centos.1.i686.rpm httpd · 软件包名 2.2.15 软件版本 15 ...