Rabbitmq——实现消费端限流 --NACK重回队列
如果是高并发下,rabbitmq服务器上收到成千上万条消息,那么当打开消费端时,这些消息必定喷涌而来,导致消费端消费不过来甚至挂掉都有可能。
在非自动确认的模式下,可以采用限流模式,rabbitmq 提供了服务质量保障qos机制来控制一次消费消息数量。
下面直接上代码:
生产端:
1 package com.zxy.demo.rabbitmq;
2
3 import java.io.IOException;
4 import java.util.concurrent.TimeoutException;
5
6 import com.rabbitmq.client.AMQP;
7 import com.rabbitmq.client.Channel;
8 import com.rabbitmq.client.ConfirmListener;
9 import com.rabbitmq.client.Connection;
10 import com.rabbitmq.client.ConnectionFactory;
11 import com.rabbitmq.client.ReturnListener;
12 import com.rabbitmq.client.AMQP.BasicProperties;
13
14 public class Producter {
15
16 public static void main(String[] args) throws IOException, TimeoutException {
17 // TODO Auto-generated method stub
18 ConnectionFactory factory = new ConnectionFactory();
19 factory.setHost("192.168.10.110");
20 factory.setPort(5672);
21 factory.setUsername("guest");
22 factory.setPassword("guest");
23 factory.setVirtualHost("/");
24 Connection conn = factory.newConnection();
25 Channel channel = conn.createChannel();
26 String exchange001 = "exchange_001";
27 String queue001 = "queue_001";
28 String routingkey = "mq.topic";
29 String body = "hello rabbitmq!===============限流策略";
30 // 开启确认模式
31 channel.confirmSelect();
32 // 循环发送多条消息
33 for(int i = 0 ;i<10;i++){
34 channel.basicPublish(exchange001, routingkey, null, body.getBytes());
35 }
36
37 // 添加一个返回监听========消息返回模式重要添加
38 channel.addConfirmListener(new ConfirmListener() {
39
40 @Override
41 public void handleNack(long deliveryTag, boolean multiple) throws IOException {
42 System.out.println("===========NACK============");
43
44 }
45
46 @Override
47 public void handleAck(long deliveryTag, boolean multiple) throws IOException {
48 System.out.println("===========ACK============");
49
50 }
51 });
52 }
53
54 }
消费端:
1 package com.zxy.demo.rabbitmq;
2
3 import java.io.IOException;
4 import java.util.concurrent.TimeoutException;
5
6 import com.rabbitmq.client.Channel;
7 import com.rabbitmq.client.Connection;
8 import com.rabbitmq.client.ConnectionFactory;
9
10 public class Receiver {
11
12 public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
13 // TODO Auto-generated method stub
14 ConnectionFactory factory = new ConnectionFactory();
15 factory.setHost("192.168.10.110");
16 factory.setPort(5672);
17 factory.setUsername("guest");
18 factory.setPassword("guest");
19 factory.setVirtualHost("/");
20 Connection conn = factory.newConnection();
21 Channel channel = conn.createChannel();
22 String exchange001 = "exchange_001";
23 String queue001 = "queue_001";
24 String routingkey = "mq.*";
25 channel.exchangeDeclare(exchange001, "topic", true, false, null);
26 channel.queueDeclare(queue001, true, false, false, null);
27 channel.queueBind(queue001, exchange001, routingkey);
28 // 设置限流策略
29 // channel.basicQos(获取消息最大数[0-无限制], 依次获取数量, 作用域[true作用于整个channel,false作用于具体消费者]);
30 channel.basicQos(0, 2, false);
31 // 自定义消费者
32 MyConsumer myConsumer = new MyConsumer(channel);
33 // 进行消费,签收模式一定要为手动签收
34 Thread.sleep(3000);
35 channel.basicConsume(queue001, false, myConsumer);
36 }
37
38 }
自定义消费者:
1 package com.zxy.demo.rabbitmq;
2
3 import java.io.IOException;
4
5 import com.rabbitmq.client.AMQP.BasicProperties;
6 import com.rabbitmq.client.Channel;
7 import com.rabbitmq.client.DefaultConsumer;
8 import com.rabbitmq.client.Envelope;
9
10 /**
11 * 可以继承,可以实现,实现的话要覆写的方法比较多,所以这里用了继承
12 *
13 */
14 public class MyConsumer extends DefaultConsumer{
15 private Channel channel;
16 public MyConsumer(Channel channel) {
17 super(channel);
18 // TODO Auto-generated constructor stub
19 this.channel=channel;
20 }
21
22 @Override
23 public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
24 throws IOException {
25 System.out.println("消费标签:"+consumerTag);
26 System.out.println("envelope.getDeliveryTag():==="+envelope.getDeliveryTag());
27 System.out.println("envelope.getExchange():==="+envelope.getExchange());
28 System.out.println("envelope.getRoutingKey():==="+envelope.getRoutingKey());
29 System.out.println("body:==="+new String(body));
30 // 手动签收,一定要有消费者签收,如果没有如下代码,则限流模式下,仅能打印出来channel.basicQos(0, 2, false);第二参数的2条信息
31 channel.basicAck(envelope.getDeliveryTag(), false);
32 }
33
34
35 }
重回队列模式,是当投递消息失败时,让该消息重新回到队列的模式,该模式需要手动签收,并需要在消费者中进行判断,调用重回队列的确认模式
代码如下
生产端:
1 package com.zxy.demo.rabbitmq;
2
3 import java.io.IOException;
4 import java.util.HashMap;
5 import java.util.Map;
6 import java.util.concurrent.TimeoutException;
7
8 import org.springframework.amqp.core.Message;
9
10 import com.rabbitmq.client.AMQP.BasicProperties;
11 import com.rabbitmq.client.Channel;
12 import com.rabbitmq.client.ConfirmListener;
13 import com.rabbitmq.client.Connection;
14 import com.rabbitmq.client.ConnectionFactory;
15 import com.rabbitmq.client.ReturnListener;
16
17 public class Producter {
18
19 public static void main(String[] args) throws IOException, TimeoutException {
20 // TODO Auto-generated method stub
21 ConnectionFactory factory = new ConnectionFactory();
22 factory.setHost("192.168.10.110");
23 factory.setPort(5672);
24 factory.setUsername("guest");
25 factory.setPassword("guest");
26 factory.setVirtualHost("/");
27 Connection conn = factory.newConnection();
28 Channel channel = conn.createChannel();
29 String exchange001 = "exchange_001";
30 String queue001 = "queue_001";
31 String routingkey = "mq.topic";
32
33 // 循环发送多条消息
34 for(int i = 0 ;i<5;i++){
35 String body = "hello rabbitmq!===============ACK&重回队列,第"+i+"条";
36 Map<String,Object> head = new HashMap<>();
37 head.put("n", i);
38 BasicProperties properties = new BasicProperties(null, "utf-8", head, 2, 1, null, null, null, null, null, null, null, null, null);
39
40 channel.basicPublish(exchange001, routingkey, properties, body.getBytes());
41 }
42
43 }
44
45 }
消费端:
1 package com.zxy.demo.rabbitmq;
2
3 import java.io.IOException;
4 import java.util.concurrent.TimeoutException;
5
6 import com.rabbitmq.client.Channel;
7 import com.rabbitmq.client.Connection;
8 import com.rabbitmq.client.ConnectionFactory;
9
10 public class Receiver {
11
12 public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
13 // TODO Auto-generated method stub
14 ConnectionFactory factory = new ConnectionFactory();
15 factory.setHost("192.168.10.110");
16 factory.setPort(5672);
17 factory.setUsername("guest");
18 factory.setPassword("guest");
19 factory.setVirtualHost("/");
20 Connection conn = factory.newConnection();
21 Channel channel = conn.createChannel();
22 String exchange001 = "exchange_001";
23 String queue001 = "queue_001";
24 String routingkey = "mq.*";
25 channel.exchangeDeclare(exchange001, "topic", true, false, null);
26 channel.queueDeclare(queue001, true, false, false, null);
27 channel.queueBind(queue001, exchange001, routingkey);
28 // 自定义消费者
29 MyConsumer myConsumer = new MyConsumer(channel);
30 // 进行消费,签收模式一定要为手动签收
31 channel.basicConsume(queue001, false, myConsumer);
32 }
33
34 }
自定义消费者:
1 package com.zxy.demo.rabbitmq;
2
3 import java.io.IOException;
4
5 import com.rabbitmq.client.AMQP.BasicProperties;
6 import com.rabbitmq.client.Channel;
7 import com.rabbitmq.client.DefaultConsumer;
8 import com.rabbitmq.client.Envelope;
9
10 /**
11 * 可以继承,可以实现,实现的话要覆写的方法比较多,所以这里用了继承
12 *
13 */
14 public class MyConsumer extends DefaultConsumer{
15 private Channel channel;
16 public MyConsumer(Channel channel) {
17 super(channel);
18 // TODO Auto-generated constructor stub
19 this.channel=channel;
20 }
21
22 @Override
23 public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
24 throws IOException {
25 System.out.println("消费标签:"+consumerTag);
26 System.out.println("envelope.getDeliveryTag():==="+envelope.getDeliveryTag());
27 System.out.println("envelope.getExchange():==="+envelope.getExchange());
28 System.out.println("envelope.getRoutingKey():==="+envelope.getRoutingKey());
29 System.out.println("body:==="+new String(body));
30 System.out.println("===================休眠以便查看===============");
31 try {
32 Thread.sleep(2000);
33 } catch (InterruptedException e) {
34 // TODO Auto-generated catch block
35 e.printStackTrace();
36 }
37 // 手动签收
38 Integer i = (Integer) properties.getHeaders().get("n");
39 System.out.println("iiiiiiiiiiiiiiiii======================================================"+i);
40 if(i==1) {
41 channel.basicNack(envelope.getDeliveryTag(),false, true);//第三个参数为是否重返队列
42 }else {
43 channel.basicAck(envelope.getDeliveryTag(), false);
44 }
45 }
46
47
48 }
下面是重回队列执行结果,可以看到当消费完后第一条不断的被扔回队列然后消费再扔回。
1 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
2 envelope.getDeliveryTag():===1
3 envelope.getExchange():===exchange_001
4 envelope.getRoutingKey():===mq.topic
5 body:===hello rabbitmq!===============ACK&重回队列,第0条
6 ===================休眠以便查看===============
7 iiiiiiiiiiiiiiiii======================================================0
8 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
9 envelope.getDeliveryTag():===2
10 envelope.getExchange():===exchange_001
11 envelope.getRoutingKey():===mq.topic
12 body:===hello rabbitmq!===============ACK&重回队列,第1条
13 ===================休眠以便查看===============
14 iiiiiiiiiiiiiiiii======================================================1
15 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
16 envelope.getDeliveryTag():===3
17 envelope.getExchange():===exchange_001
18 envelope.getRoutingKey():===mq.topic
19 body:===hello rabbitmq!===============ACK&重回队列,第2条
20 ===================休眠以便查看===============
21 iiiiiiiiiiiiiiiii======================================================2
22 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
23 envelope.getDeliveryTag():===4
24 envelope.getExchange():===exchange_001
25 envelope.getRoutingKey():===mq.topic
26 body:===hello rabbitmq!===============ACK&重回队列,第3条
27 ===================休眠以便查看===============
28 iiiiiiiiiiiiiiiii======================================================3
29 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
30 envelope.getDeliveryTag():===5
31 envelope.getExchange():===exchange_001
32 envelope.getRoutingKey():===mq.topic
33 body:===hello rabbitmq!===============ACK&重回队列,第4条
34 ===================休眠以便查看===============
35 iiiiiiiiiiiiiiiii======================================================4
36 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
37 envelope.getDeliveryTag():===6
38 envelope.getExchange():===exchange_001
39 envelope.getRoutingKey():===mq.topic
40 body:===hello rabbitmq!===============ACK&重回队列,第1条
41 ===================休眠以便查看===============
42 iiiiiiiiiiiiiiiii======================================================1
43 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
44 envelope.getDeliveryTag():===7
45 envelope.getExchange():===exchange_001
46 envelope.getRoutingKey():===mq.topic
47 body:===hello rabbitmq!===============ACK&重回队列,第1条
48 ===================休眠以便查看===============
49 iiiiiiiiiiiiiiiii======================================================1
50 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
51 envelope.getDeliveryTag():===8
52 envelope.getExchange():===exchange_001
53 envelope.getRoutingKey():===mq.topic
54 body:===hello rabbitmq!===============ACK&重回队列,第1条
55 ===================休眠以便查看===============
56 iiiiiiiiiiiiiiiii======================================================1
57 消费标签:amq.ctag-eeeaa9jgrJ3tDhtQR2XReg
58 envelope.getDeliveryTag():===9
59 envelope.getExchange():===exchange_001
60 envelope.getRoutingKey():===mq.topic
61 body:===hello rabbitmq!===============ACK&重回队列,第1条
62 ===================休眠以便查看===============
Rabbitmq——实现消费端限流 --NACK重回队列的更多相关文章
- Rabbitmq之高级特性——实现消费端限流&NACK重回队列
如果是高并发下,rabbitmq服务器上收到成千上万条消息,那么当打开消费端时,这些消息必定喷涌而来,导致消费端消费不过来甚至挂掉都有可能. 在非自动确认的模式下,可以采用限流模式,rabbitmq ...
- SpringBoot 整合 RabbitMQ(包含三种消息确认机制以及消费端限流)
目录 说明 生产端 消费端 说明 本文 SpringBoot 与 RabbitMQ 进行整合的时候,包含了三种消息的确认模式,如果查询详细的确认模式设置,请阅读:RabbitMQ的三种消息确认模式 同 ...
- RabbitMQ 消费端限流、TTL、死信队列
目录 消费端限流 1. 为什么要对消费端限流 2.限流的 api 讲解 3.如何对消费端进行限流 TTL 1.消息的 TTL 2.队列的 TTL 死信队列 实现死信队列步骤 总结 消费端限流 1. 为 ...
- RabbitMQ消费端限流策略(十)
消费端限流: 什么是消费端限流? 场景: 我们RabbitMQ服务器有上万条未处理的消息,我们随便打开一个消费者客户端,会出现下面情况: 巨量的消息瞬间全部推送过来,但是我们单个客户端无法同时处理这么 ...
- 面试官:RabbitMQ怎么实现消费端限流
哈喽!大家好,我是小奇,一位不靠谱的程序员 小奇打算以轻松幽默的对话方式来分享一些技术,如果你觉得通过小奇的文章学到了东西,那就给小奇一个赞吧 文章持续更新 一.前言 RabbitMQ有很多高级特性, ...
- RabbitMQ高级之消息限流与延时队列
人生终将是场单人旅途,孤独之前是迷茫,孤独过后是成长. 楔子 本篇是消息队列RabbitMQ的第五弹. 上篇本来打算讲述RabbitMQ的一些高级用法: 如何保证消息的可靠性? 消息队列如何进行限流? ...
- jmeter压测IP欺骗绕过服务端限流
1.环境声明 jmeter3.0 后端为内网环境 2.检查内网闲置的ip 工具地址,无需复杂安装,解压点击就可以用啦~~ https://pan.baidu.com/s/1Yzs1vezfFMoy-m ...
- 消费端ACK和重回队列
使用场景 消费端ACK和重回队列 消费端ACK使用场景: 1.消费端进行消费的时候,如果由于业务异常我们可以进行日志记录,然后进行补偿. 2.由于服务器宕机等严重问题,那我们就需要手工进行ACK保障消 ...
- 服务接口API限流 Rate Limit
一.场景描述 很多做服务接口的人或多或少的遇到这样的场景,由于业务应用系统的负载能力有限,为了防止非预期的请求对系统压力过大而拖垮业务应用系统. 也就是面对大流量时,如何进行流量控制? 服务接口的流量 ...
随机推荐
- JVM插码之四:Java动态代理机制的对比(JDK 和CGLIB,Javassist,ASM)
一.class文件简介及加载 Java编译器编译好Java文件之后,产生.class 文件在磁盘中.这种class文件是二进制文件,内容是只有JVM虚拟机能够识别的机器码.JVM虚拟机读取字节码文件, ...
- 校赛热身 Problem C. Sometimes Naive (状压dp)
题解: 列举每一种3的倍数的组合,开始先求出3条边的可行解,则 六条边的可行解可以由两个三条边得来. 详见代码解析 #include<bits/stdc++.h> using namesp ...
- Java-API:java.util.list
ylbtech-Java-API:java.util.list 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 5.返回顶部 1. https://docs.oracle.co ...
- HTTP-Runoob:HTTP请求方法
ylbtech-HTTP-Runoob:HTTP请求方法 1.返回顶部 1. HTTP请求方法 根据HTTP标准,HTTP请求可以使用多种请求方法. HTTP1.0定义了三种请求方法: GET, PO ...
- ruby on rails 中render的
Ruby rails页面跳转代码如下: 1.render(:text => string) 2.render(:inline => string, [:type => "r ...
- java基础知识(14)---API
API:(Application Programming Interface,编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件的以访问一组例程的能力,而又无需访问源码,或理 ...
- springmvc----demo3---rest风格---bai
input_stu_path.jsp: showinput_stu_path.jsp:
- web基础(五)Jquery
jQuery是一个快速的,简洁的javaScript库(占空间特别小,但功能强大!兼容性极强!),这个库里封装了一些方法,使用户能更方便地处理HTMLdocuments.events.实现动画效果,并 ...
- ffmpeg初体验
ffmpeg是一个多平台多媒体处理工具,处理视频和音频的功能非常强大.目前在网上搜到的iOS上使用FFMPEG的资料都比较陈旧,而FFMPEG更新迭代比较快: 且网上的讲解不够详细,对于初次接触FFM ...
- python中匹配中文,解决不匹配,乱码等问题
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal 字符串前加 ur‘str’即可;