热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

netcore下RabbitMQ队列、死信队列、延时队列及小应用

原标题:netcore下RabbitMQ队列、死信队列、延时队列及小应用关于安装rabbitmq这里一笔掠过了。下面进入正题:1.新建aspnetcor

原标题:netcore下RabbitMQ队列、死信队列、延时队列及小应用

关于安装rabbitmq这里一笔掠过了。

下面进入正题:

1.新建aspnetcorewebapi空项目,NormalQueue,删除controllers文件夹已经无关的文件,这里为了偷懒不用console控制台:

public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHostedService
();
builder.Services.AddHostedService
();
builder.Services.AddHostedService
();
var app = builder.Build();
/文章来源站点https://www.yii666.com// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapGet(
"/normal/{message}", ([FromRoute] string message) =>
{
ConnectionFactory factory
= new ConnectionFactory();
factory.HostName
= "localhost";
factory.Port
= 5672;
using (IConnection cOnnection= factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
var queueName = "rbTest202301";
channel.QueueDeclare(queueName,
true, false, false, null);
{
string sendMessage = string.Format("Message_{0}", message);
byte[] buffer = Encoding.UTF8.GetBytes(sendMessage);
IBasicProperties basicProperties
= channel.CreateBasicProperties();
basicProperties.DeliveryMode
= 2; //持久化 1=非持久化
channel.BasicPublish("", queueName, basicProperties, buffer);
Console.WriteLine(
"消息发送成功:" + sendMessage);
}
}
}
});
app.MapGet(
"/deadletterexchange/{message}",([FromRoute] string message) =>{
DeadLetterExchange.Send(message);
});
app.MapGet(
"/delayexchange/{message}", ([FromRoute] string message) => {
DelayExchange.SendMessage(message);
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}

大概的介绍一下program文件:

这里有三个mini控制器,从这里发送对应的消息到rabbitmq

"/normal/{message}" 普通队列,

"/deadletterexchange/{message}" 死信队列

"/deadletterexchange/{message}" 延时队列

      builder.Services.AddHostedService();
builder.Services.AddHostedService
();
builder.Services.AddHostedService
();

这里就是消费的服务,注册成HostedService。

ConsumerService代码如下:

public class ConsumerService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine(
"normal Rabbitmq消费端开始工作!");
while (!stoppingToken.IsCancellationRequested)
{
ConnectionFactory factory
= new ConnectionFactory();
factory.HostName
= "localhost";
factory.Port
= 5672;

IConnection connection
= factory.CreateConnection();
{
IModel channel
= connection.CreateModel();
{
var queueName = "rbTest202301";
channel.QueueDeclare(queueName,
true, false, false, null);
//输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息
channel.BasicQos(0, 1, false);
//在队列上定义一个消费者
var cOnsumer= new EventingBasicConsumer(channel);
channel.BasicConsume(queueName,
false, consumer);
consumer.Received
+= (ch, ea) =>
{
byte[] bytes = ea.Body.ToArray();
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(
"队列消息:" + str.ToString());
//回复确认
channel.BasicAck(ea.DeliveryTag, false);
};
}
}
await Task.Delay(5000);
}
}
}

DeadLetterExchangeConsuerService代码如下:

public class DeadLetterExchangeConsuerService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine(
"RabbitMQ消费端死信队列开始工作");
while (!stoppingToken.IsCancellationRequested)
{
DeadLetterExchange.Consumer();
await Task.Delay(5000);
}
}
}


public class DeadLetterExchange
{
public static string dlxExchange = "dlx.exchange";
public static string dlxQueueName = "dlx.queue";
static string exchange = "direct-exchange";
static string queueName = "queue_Testdlx";
static string dlxExchangeKey = "x-dead-letter-exchange";
static string dlxQueueKey = "x-dead-letter-rounting-key";
public static void Send(string message)
{
using (var cOnnection= new ConnectionFactory() { HostName = "localhost", Port = 5672 }.CreateConnection())
{
using(var channel = connection.CreateModel())
{

channel.ExchangeDeclare(exchange, ExchangeType.Direct,
true, false); //创建交换机
channel.QueueDeclare(queueName, true, false, false,new Dictionary<string, object>
{
{ dlxExchangeKey,dlxExchange },
{dlxQueueKey,dlxQueueName }
});
// 创建队列
channel.QueueBind(queueName, exchange, queueName);
var properties = channel.CreateBasicProperties();
properties.Persistent
= true;//持久化
channel.BasicPublish(exchange,queueName,properties,Encoding.UTF8.GetBytes(message));
Console.WriteLine($
"向队列:{queueName}发送消息:{message}");
}
}
}

public static void Consumer()
{
var cOnnection= new ConnectionFactory() { HostName = "localhost", Port = 5672 }.CreateConnection();
var channel = connection.CreateModel();
channel.ExchangeDeclare(dlxExchange, ExchangeType.Direct,
true, false); //创建sixin交换机
channel.QueueDeclare(dlxQueueName, true, false, false); // 创建sixin队列
channel.QueueBind(dlxQueueName, dlxExchange, dlxQueueName); //绑定sixin队列sixin交换机

channel.ExchangeDeclare(exchange, ExchangeType.Direct,
true, false); //创建交换机
channel.QueueDeclare(queueName, true, false, false, new Dictionary<string, object>
{
{ dlxExchangeKey,dlxExchange },
{dlxQueueKey,dlxQueueName }
});
// 创建队列
channel.QueueBind(queueName, exchange, queueName);
var cOnsumer= new EventingBasicConsumer(channel);
channel.BasicQos(
0, 1, false);
consumer.Received
+= (model, ea) =>
{
var message = Encoding.UTF8.GetString(ea.Body.ToArray());
Console.WriteLine($
"队列{queueName}消费消息:{message},不做ack确认");
channel.BasicNack(ea.DeliveryTag,
false, requeue: false);
};
channel.BasicConsume(queueName, autoAck:
false, consumer);
}
}

DelayExchangeConsumerService代码如下:

public class DelayExchangeConsumerService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine(
"RabbitMQ消费端延迟队列开始工作");
while (!stoppingToken.IsCancellationRequested)
{

DelayExchange.Consumer();
await Task.Delay(5000);
}
}
}


public class DelayExchange
{
public static void SendMessage(string message)
{
//死信交换机
string dlxexChange = "dlx.exchange";
//死信队列
string dlxQueueName = "dlx.queue";
//消息交换机
string exchange = "direct-exchange";
//消息队列
string queueName = "delay_queue";
using (var cOnnection= new ConnectionFactory() { HostName = "localhost", Port = 5672 }.CreateConnection())
{
using (var channel = connection.CreateModel())
{
////创建死信交换机
//channel.ExchangeDeclare(dlxexChange, type: ExchangeType.Direct, durable: true, autoDelete: false);
////创建死信队列
//channel.QueueDeclare(dlxQueueName, durable: true, exclusive: false, autoDelete: false);
////死信队列绑定死信交换机
//channel.QueueBind(dlxQueueName, dlxexChange, routingKey: dlxQueueName);
// 创建消息交换机
channel.ExchangeDeclare(exchange, type: ExchangeType.Direct, durable: true, autoDelete: false);
//创建消息队列,并指定死信队列,和设置这个队列的消息过期时间为10s
channel.QueueDeclare(queueName, durable: true, exclusive: false, autoDelete: false, arguments:
new Dictionary<string, object> {
{
"x-dead-letter-exchange",dlxexChange}, //设置当前队列的DLX(死信交换机)
{ "x-dead-letter-routing-key",dlxQueueName}, //设置DLX的路由key,DLX会根据该值去找到死信消息存放的队列
{ "x-message-ttl",10000} //设置队列的消息过期时间
});
//消息队列绑定消息交换机
channel.QueueBind(queueName, exchange, routingKey: queueName);
var properties = channel.CreateBasicProperties();
properties.Persistent
= true;
//properties.Expiration = "5000";发布消息,延时5s
//发布消息
channel.BasicPublish(exchange: exchange,
routingKey: queueName,
basicProperties: properties,
body: Encoding.UTF8.GetBytes(message));
Console.WriteLine($
"{DateTime.Now},向队列:{queueName}发送消息:{message}");
}
}
}
public static void Consumer()
{
//死信交换机
string dlxexChange = "dlx.exchange";
//死信队列
string dlxQueueName = "dlx.queue";
var cOnnection= new ConnectionFactory() { HostName = "localhost", Port = 5672 }.CreateConnection();
{
//创建信道
var channel = connection.CreateModel();
{
//创建死信交换机
channel.ExchangeDeclare(dlxexChange, type: ExchangeType.Direct, durable: true, autoDelete: false);
//创建死信队列
channel.QueueDeclare(dlxQueueName, durable: true, exclusive: false, autoDelete: false);
//死信队列绑定死信交换机
channel.QueueBind(dlxQueueName, dlxexChange, routingKey: dlxQueueName);
var consumwww.yii666.comer = new EventingBasicConsumer(channel);
channel.BasicQos(prefetchSize:
0, prefetchCount: 1, global: true);
consumer.Received
+= (model, ea) =>
{
//处理业务
var message = Encoding.UTF8.GetString(ea.Body.ToArray());
Console.WriteLine($
"{DateTime.Now},队列{dlxQueueName}消费消息:{message}");
channel.BasicAck(ea.DeliveryTag,
false);
};
channel.BasicConsume(dlxQueueName, autoAck:
false, consumer);
}
}
}
}

延时队列实际应用场景可能比较复杂,比如每条消息的过期时间不一样,收到的消息的顺序有可能会乱掉。这些不做深究,自行百度。

关于死信队列常见应用场景之一下单,支付,支付超时的各种场景,下面通过一个简单的例子模拟一下

同样的新建一个空的webapi项目DeadLetterQueue,

program代码如下:

public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHostedService
();
builder.Services.AddHostedService
();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapGet(
"/normal/{message}", ([FromRoute] string message) =>
{
ConnectionFactory factory
= new ConnectionFactory();
factory.HostName
= "localhost";
factory.Port
= 5672;
using (IConnection cOnnection= factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
var queueName = "rbTest2023010";

//channel.ExchangeDeclare("exchange.dlx", ExchangeType.Direct, true);
//channel.QueueDeclare("queue.dlx", true, false, false, null);
channel.ExchangeDeclare("exchange.normal", ExchangeType.Fanout, true);
channel.QueueDeclare(queueName,
true, false, false,
new Dictionary<string, object>
{
{
"x-message-ttl" ,10000},
{
"x-dead-letter-exchange","exchange.dlx" },
{
"x-dead-letter-routing-key","routingkey" }
}
);

channel.QueueBind(queueName,
"exchange.normal", "");
{
string sendMessage = string.Format("Message_{0}", message);
byte[] buffer = Encoding.UTF8.GetBytes(sendMessage);
IBasicProperties basicProperties
= channel.CreateBasicProperties();
basicProperties.DeliveryMode
= 2; //持久化 1=非持久化
channel.BasicPublish("exchange.normal", queueName, basicProperties, buffer);
Console.WriteLine($
"{DateTime.Now}消息发送成功:{sendMessage}" );
}
}
}
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}

下单后消费代码ConsumerService如下

public class ConsumerService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine(
"normal Rabbitmq消费端开始工作!");
while (!stoppingToken.IsCancellationRequested)
{
ConnectionFactory factory
= new ConnectionFactory();
factory.HostName
= "localhost";
factory.Port
= 5672;
IConnection connection
= factory.CreateConnection();
{
IModel channel
= connection.CreateModel();
{
var queueName = "rbTest2023010";
channel.ExchangeDeclare(
"exchange.normal", ExchangeType.Fanout, true);
channel.QueueDeclare(queueName,
true, false, false, new Dictionary<string, object>
{
{
"x-message-ttl" ,10000},
{
"x-dead-letter-exchange","exchange.dlx" },
{
"x-dead-letter-routing-key","routingkey" }
});
channel.QueueBind(queueName,
"exchange.normal", "");
//输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息
channel.BasicQos(0, 1, false);
//在队列上定义一个消费者
var cOnsumer= new EventingBasicConsumer(channel);
channel.BasicConsume(queueName,
false, consumer);
consumer.Received
+= (ch, ea) =>
{
byte[] bytes = ea.Body.ToArray();
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine($
"{DateTime.Now}来自死信队列获取的消息: {str.ToString()}");
//回复确认
if (str.Contains("跳过")) //假设超时不处理,留给后面deadconsumerservice处理
{
Console.WriteLine($
"{DateTime.Now}来自死信队列获取的消息: {str.ToString()},该消息被拒绝");
channel.BasicNack(ea.DeliveryTag,
false,false);
}
else //正常消息处理
{
Console.WriteLine($
"{DateTime.Now}来自死信队列获取的消息: {str.ToString()},该消息被接受");
channel.BasicAck(ea.DeliveryTag,
false);
}
};
}
}
await Task.文章来源地址19049.htmlDelay(5000);
}
}
}

通过模拟发送的消息加入跳过两个字会拒收这条消息,这样就会跳到设置的exchange.dlx交换机队列去,如果没有跳过那么这条消息就正常处理掉,消费确认。

超时不处理后我们通过新的消费服务DeadConsumerService来处理这异常的消费,比如回复库存,订单状态改为取消等等

public class DeadConsumerService:BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine(
"normal Rabbitmq消费端开始工作!");
while (!stoppingToken.IsCancellationRequested)
{
ConnectionFactory factory
= new ConnectionFactory();
factory.HostName
= "localhost";
factory.Port
= 5672;

IConnection connection
= factory.CreateConnection();
{
IModel channel
= connection.CreateModel();
{
var queueName = "queue.dlx";
channel.ExchangeDeclare(
"exchange.dlx", ExchangeType.Direct, true);
channel.QueueDeclare(
"queue.dlx", true, false, false, null);

channel.QueueDeclare(queueName,
true, false, false, null);
channel.QueueBind(queueName,
"exchange.dlx", "");
//输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息
channel.BasicQos(0, 1, false);
//在队列上定义一个消费者
var cOnsumer= new EventingBasicConsumer(channel);
channel.BasicConsume(
"queue.dlx", false, consumer);
consumer.Received
+= (ch, ea) =>
{
byte[] bytes = ea.Body.ToArray();
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine($
"{DateTime.Now}超时未处理的消息: {str.ToString()}");
//回复确认
{
channel.BasicAck(ea.DeliveryTag,
false);
}
};
文章来源地址19049.html}
}
await Task.Delay(5000);
www.yii666.com }
}
}

运行结果:

关于rabbitmq的死信队列和延时队列的介绍什么的这里不去贴baidu了,应用demo就这么多了,代码这里exercisebook/RabbitMQ.Test at main liuzhixin405/exercisebook (github.com) 。小面分享一个完整一点的例子。

exercisebook/cat.seckill/cat.seckill at main liuzhixin405/exercisebook (github.com)

感觉自己还是不合适写这些玩意儿,没有那么细心和耐心,有这时间真不如写写demo。

来源于:netcore下RabbitMQ队列、死信队列、延时队列及小应用


推荐阅读
  • 并发编程 12—— 任务取消与关闭 之 shutdownNow 的局限性
    Java并发编程实践目录并发编程01——ThreadLocal并发编程02——ConcurrentHashMap并发编程03——阻塞队列和生产者-消费者模式并发编程04——闭锁Co ... [详细]
  • 深入解析SpringMVC核心组件:DispatcherServlet的工作原理
    本文详细探讨了SpringMVC的核心组件——DispatcherServlet的运作机制,旨在帮助有一定Java和Spring基础的开发人员理解HTTP请求是如何被映射到Controller并执行的。文章将解答以下问题:1. HTTP请求如何映射到Controller;2. Controller是如何被执行的。 ... [详细]
  • 深入解析Java多线程与并发库的应用:空中网实习生面试题详解
    本文详细探讨了Java多线程与并发库的高级应用,结合空中网在挑选实习生时的面试题目,深入分析了相关技术要点和实现细节。文章通过具体的代码示例展示了如何使用Semaphore和SynchronousQueue来管理线程同步和任务调度。 ... [详细]
  • 本文探讨了如何通过一系列技术手段提升Spring Boot项目的并发处理能力,解决生产环境中因慢请求导致的系统性能下降问题。 ... [详细]
  • 使用WinForms 实现 RabbitMQ RPC 示例
    本文通过两个WinForms应用程序演示了如何使用RabbitMQ实现远程过程调用(RPC)。一个应用作为客户端发送请求,另一个应用作为服务端处理请求并返回响应。 ... [详细]
  • 本文深入探讨了SQL数据库中常见的面试问题,包括如何获取自增字段的当前值、防止SQL注入的方法、游标的作用与使用、索引的形式及其优缺点,以及事务和存储过程的概念。通过详细的解答和示例,帮助读者更好地理解和应对这些技术问题。 ... [详细]
  • 实用正则表达式有哪些
    小编给大家分享一下实用正则表达式有哪些,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下 ... [详细]
  • Java项目分层架构设计与实践
    本文探讨了Java项目中应用分层的最佳实践,不仅介绍了常见的三层架构(Controller、Service、DAO),还深入分析了各层的职责划分及优化建议。通过合理的分层设计,可以提高代码的可维护性、扩展性和团队协作效率。 ... [详细]
  • 本文详细介绍了如何在Kendo UI for jQuery的数据管理组件中,将行标题字段呈现为锚点(即可点击链接),帮助开发人员更高效地实现这一功能。通过具体的代码示例和解释,即使是新手也能轻松掌握。 ... [详细]
  • 由二叉树到贪心算法
    二叉树很重要树是数据结构中的重中之重,尤其以各类二叉树为学习的难点。单就面试而言,在 ... [详细]
  • Linux环境下进程间通信:深入解析信号机制
    本文详细探讨了Linux系统中信号的生命周期,从信号生成到处理函数执行完毕的全过程,并介绍了信号编程中的注意事项和常见应用实例。通过分析信号在进程中的注册、注销及处理过程,帮助读者理解如何高效利用信号进行进程间通信。 ... [详细]
  • Spring Boot 中静态资源映射详解
    本文深入探讨了 Spring Boot 如何简化 Web 应用中的静态资源管理,包括默认的静态资源映射规则、WebJars 的使用以及静态首页的处理方法。通过本文,您将了解如何高效地管理和引用静态资源。 ... [详细]
  • 本文详细介绍了Java中实现异步调用的多种方式,包括线程创建、Future接口、CompletableFuture类以及Spring框架的@Async注解。通过代码示例和深入解析,帮助读者理解并掌握这些技术。 ... [详细]
  • 本文深入探讨了UNIX/Linux系统中的进程间通信(IPC)机制,包括消息传递、同步和共享内存等。详细介绍了管道(Pipe)、有名管道(FIFO)、Posix和System V消息队列、互斥锁与条件变量、读写锁、信号量以及共享内存的使用方法和应用场景。 ... [详细]
  • 本文探讨了Web开发与游戏开发之间的主要区别,旨在帮助开发者更好地理解两种开发领域的特性和需求。文章基于作者的实际经验和网络资料整理而成。 ... [详细]
author-avatar
ouyan1985_998
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有