Channel
For simplicity and ease of infrastructure management, there is only ever a single TCP connection to rabbit.
Channels exist as a sort of virtual connection to rabbit, and each acts independently of the others.
Code
Opening a Channel
var connectionFactory = new ConnectionFactory();
var connection = await connectionFactory.CreateConnectionAsync();
var channel = await connection.CreateChannelAsync();
// ... use the channel to declare topology, publish, consumeClosing a Channel
If a message has been consumed then marked as Ack’ed after the channel is closed, the message will be re-queued. Thus you must ensure you close the channel when it is no longer needed.
// create channel
// do some work
// close the channel when it is no longer needed
await channel.CloseAsync();Error Handling
Channels may fail or close for multiple reasons; rabbit often has a “soft-failure” approach allowing you to see why the failure happened, and gives you the opportunity to recover. The following handlers may be implemented.
channel.CallbackExceptionAsync += async (_, args) =>
{
Console.WriteLine(args.Exception);
await Task.CompletedTask;
};
channel.ChannelShutdownAsync += async (_, args) =>
{
Console.WriteLine(args.ReplyText);
await Task.CompletedTask;
};Management
Channel Leak
When a channel is not closed, resulting in a open channel that is not being used. This consumes the channel count and can lead to large issues.
High Channel Churn
When channels are open and closed rapidly. A count higher than 100/second is pretty bad, and indicates sub-optimal performance.
Channels should be open for as long as possible while they are needed.