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());
}
}
我有上面的代码,我对线程安全很好奇。
我不确定,但我想ConnectionFactory
是线程安全的。但是IConnection
线程安全吗?我应该为每个请求创建一个连接吗?还是一个单一的持久连接?那么通道(IModel
)呢?
另外,我应该将连接存储为 ThreadLocal 吗?或者我应该为每个请求创建一个连接?