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.
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
)?
Also, should I store the connection as ThreadLocal? Or should I create a connection per request?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With