RocketMQ是一個開源的分布式消息中間件,支持高可靠、高性能、可伸縮的消息傳遞。在C#中使用RocketMQ發送和接收消息需要使用RocketMQ的客戶端庫。
以下是使用RocketMQ C#客戶端庫發送和接收消息的基本示例:
發送消息:
using System;
using RocketMQ.Client;
using RocketMQ.Client.Producer;
class Program
{
static void Main(string[] args)
{
DefaultMQProducer producer = new DefaultMQProducer("ProducerGroup");
producer.NamesrvAddr = "127.0.0.1:9876";
try
{
producer.Start();
Message msg = new Message("TopicTest", "TagA", "Hello RocketMQ".GetBytes());
SendResult sendResult = producer.Send(msg);
Console.WriteLine($"SendResult: {sendResult}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
finally
{
producer.Shutdown();
}
}
}
接收消息:
using System;
using RocketMQ.Client;
using RocketMQ.Client.Consumer;
class Program
{
static void Main(string[] args)
{
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("ConsumerGroup");
consumer.NamesrvAddr = "127.0.0.1:9876";
consumer.Subscribe("TopicTest", "TagA");
consumer.RegisterMessageListener((MessageListenerConcurrently)(msgs) =>
{
foreach (var msg in msgs)
{
Console.WriteLine($"Received message: {msg.Body}");
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
try
{
consumer.Start();
Console.WriteLine("Consumer started.");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
Console.ReadLine();
}
}
以上示例分別演示了如何在C#中使用RocketMQ發送和接收消息。在實陵使用RocketMQ C#客戶端庫時,需要引入RocketMQ.Client庫,并根據具體的業務需求配置Producer和Consumer的相關參數。