c#

RocketMQ C#的消息发送与接收

小樊
211
2024-08-08 22:12:42
栏目: 编程语言

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的相关参数。

0
看了该问题的人还看了