• 周三. 6月 29th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

C#使用RabbitMq队列 worke模式

admin

11月 28, 2021

//简单生产端 ui调用者

using System;
namespace RabbitMqPublishDemo
{
using MyRabbitMqService;
using System.Runtime.CompilerServices;

class Program
{
static void Main(string[] args)
{
//就是简单的队列,生产者
Console.WriteLine(“====RabbitMqPublishDemo====”);
for (int i = 0; i < 500; i++)
{
ZrfRabbitMqHelper.PublishSampleMsg(“smapleMsg”, $”nihaifengge:{i}”);
}
Console.WriteLine(“生成完毕!”);
Console.ReadLine();
}
}
}

/// <summary>
/// 简单生产者 逻辑
/// </summary>
/// <param name=”queueName”></param>
/// <param name=”msg”></param>
public static void PublishSampleMsg(string queueName, string msg)
{

using (IConnection conn = connectionFactory.CreateConnection())
{
using (IModel channel = conn.CreateModel())
{
channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
var msgBody = Encoding.UTF8.GetBytes(msg);
channel.BasicPublish(exchange: “”, routingKey: queueName, basicProperties: null, body: msgBody);
}
}
}

//简单消费端
using System;

namespace RabbitMqConsumerDemo
{
using MyRabbitMqService;
using System.Runtime.InteropServices;

class Program
{
static void Main(string[] args)
{
Console.WriteLine(“====RabbitMqConsumerDemo====”);
ZrfRabbitMqHelper.ConsumeSampleMsg(“smapleMsg”, isBasicNack: true, handleMsgStr: handleMsgStr =>
{
Console.WriteLine($”订阅到消息:{DateTime.Now}:{handleMsgStr}”);
});
Console.ReadLine();
}
}
}

#region 简单生产者后端逻辑
/// <summary>
/// 简单消费者
/// </summary>
/// <param name=”queueName”>队列名称</param>
/// <param name=”isBasicNack”>失败后是否自动放到队列</param>
/// <param name=”handleMsgStr”>有就自己对字符串的处理,如果要存储到数据库请自行扩展</param>
public static void ConsumeSampleMsg(string queueName, bool isBasicNack = false, Action<string> handleMsgStr = null)// bool ifBasicReject = false,
{
Console.WriteLine(“ConsumeSampleMsg Waiting for messages….”);
IConnection conn = connectionFactory.CreateConnection();
IModel channel = conn.CreateModel();
channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, ea) =>
{
byte[] bymsg = ea.Body.ToArray();
string msg = Encoding.UTF8.GetString(bymsg);
if (handleMsgStr != null)
{
handleMsgStr.Invoke(msg);
}
else
{
Console.WriteLine($”{DateTime.Now}->收到消息:{msg}”);
}
};
channel.BasicConsume(queueName, autoAck: true, consumer);
}
#endregion

本文来自博客园,作者:.net&new,转载请注明原文链接:https://www.cnblogs.com/wugh8726254/p/15091731.html

发表评论

您的电子邮箱地址不会被公开。