本文介绍了C# RabbitMQ 客户端线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ConnectionFactory factory = new ConnectionFactory {HostName = "localhost"};

using (IConnection connection = factory.CreateConnection())
using (IModel channel = connection.CreateModel())
{
    channel.QueueDeclare("hello", false, false, false, null);
    for (int i = 0; i < 100000; i++)
    {
        MemoryStream stream = new MemoryStream();

        var user = new User
                       {
                           Id = i
                       };

        Serializer.Serialize(stream, user);


        channel.BasicPublish("", "hello", null, stream.ToArray());

    }

}

我有上面的代码,我对线程安全很好奇.

I have the code above, and I'm curious about thread safety.

我不确定,但我想 ConnectionFactory 是线程安全的.但是 IConnection 线程安全吗?我应该为每个请求创建一个连接吗?还是一个单一的持久连接?那么通道(IModel)呢?

I am not sure, but I would imagine ConnectionFactory is thread safe. But is IConnection thread safe? Should I create a connection per request? Or rather a single persistent connection? And what about channel (IModel)?

另外,我应该将连接存储为 ThreadLocal 吗?或者我应该为每个请求创建一个连接?

Also, should I store the connection as ThreadLocal? Or should I create a connection per request?

推荐答案

IConnection 是线程安全的,IModel 不是.通常,您应该努力在应用程序的整个生命周期内保持连接打开.如果您的消费者需要打开连接才能接收消息,则尤其如此.由于网络或代理故障,检测中断连接并从中恢复非常重要.我建议阅读 Videla 和 Williams 的RabbitMQ in Action",尤其是第 6 章编写在失败中幸存的代码".

IConnection is thread safe, IModel is not. Generally you should endeavour to keep a connection open for the lifetime of your application. This is especially true if you have consumers which need an open connection in order to receive messages. It's important to detect and recover from interrupted connections, either because of network or Broker failure. I'd recommend reading 'RabbitMQ in Action' by Videla and Williams, especially chapter 6 'Writing code that survives failure'.

现在是一个无耻的插件.我是 EasyNetQ 的作者,它是 RabbitMQ 的高级 .NET API.它为您完成所有连接管理,如果网络或代理中断,它将自动重新连接并重建您的所有订阅者.它还提供开箱即用的集群和故障转移支持.试试看吧.

Now for a shameless plug. I'm the author of EasyNetQ, a high-level .NET API for RabbitMQ. It does all the connection management for you and will automatically re-connect and rebuild all your subscribers if there's a network or broker outage. It also provides cluster and fail-over support out of the box. Give it a try.

这篇关于C# RabbitMQ 客户端线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:16