C#RabbitMQ客户端线程安全 [英] C# RabbitMQ Client thread safety

查看:481
本文介绍了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是否是线程安全的?我应该根据请求创建连接吗?还是一个单一的持久连接?那IChannel呢?

I am not sure, but I would imagine ConnectionFactory is thread safe. But then I'm not sure if IConnection is thread safe? Should I create connection per request? Or rather a single persistent connection? And what about IChannel?

我还应该将连接存储为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 的作者,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客户端线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆