前面1篇讲解了基于docker的rocketmq集群搭建,现在需要进行数据生产和消费,网上找了资源,发现可以用NewLife.RocketMQ进行对接
看了最新版本的NewLife.RocketMQ 发现是基于.net5框架的版本号:2.0.2022.101,有的版本会引起bug
生产:
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//mq对象
using var mq = new Producer
{
//主题
Topic = "GPS",
//服务地址
NameServerAddress = "10.5.1.233:9876;10.5.1.236:9876",
};
mq.Start();
int i = 1;
//轮询发消息
while (true)
{
try
{
var content = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss.fff");
var message = new NewLife.RocketMQ.Protocol.Message()
{
BodyString = content,
Keys = (i++).ToString(),
Tags = i % 2 == 0 ? "even" : "odd",
Flag = 0,
WaitStoreMsgOK = true
};
//发送消息(生产消息)
var sr = mq.Publish(message);
string log = $"发送成功的消息,内容>{content}}";
Console.WriteLine(log);
Task.Delay(TimeSpan.FromMilliseconds(100)).Wait();
}
catch (Exception)
{
//throw;
}
}
}
消费
static void Main(string[] args)
{
//测试消费消息
var consumer = new NewLife.RocketMQ.Consumer
{
Topic = "GPS",
NameServerAddress = "10.5.1.233:9876;10.5.1.236:9876",
//设置每次接收消息只拉取一条信息
BatchSize = 1
};
consumer.OnConsume = (q, ms) =>
{
string mInfo = $"BrokerName={q.BrokerName},QueueId={q.QueueId},Length={ms.Length}";
Console.WriteLine(mInfo);
foreach (var item in ms.ToList())
{
string msg = $"消息:msgId={item.MsgId},key={item.Keys},产生时间【{item.BornTimestamp.ToDateTime()}】,内容>{item.Body.ToStr()}";
Console.WriteLine(msg);
}
// return false;//通知消息队:不消费消息
return true; //通知消息队:消费了消息
};
consumer.Start();
Console.WriteLine("消息接收测试");
Console.ReadLine();
}
运行如下,测试一个节点宕机也不影响生产消费