Explains connections and how they relate to senders and receivers, for more posts in this series go to Contents.
So far, we’ve been creating a ServiceBusClient to create senders and receivers. The below code illustrates a small example that sends a message to a destination and then receives a single message from that destination.
await using var serviceBusClient = new ServiceBusClient(connectionString); await using var connectionSharingSender = serviceBusClient .CreateSender(destination); await connectionSharingSender .SendMessageAsync(new ServiceBusMessage("Deep Dive")); await using var connectionSharingReceiver = serviceBusClient .CreateReceiver(destination); await connectionSharingReceiver.ReceiveMessageAsync();
The common thing that we’ve seen in the samples so far as well as in the code above is that we are the same ServiceBusClient to create senders and receivers. Let’s explore what happens under the hood with netstat while the above sample code is running:
netstat -na | find "5671" TCP 192.168.1.7:60470 188.8.131.52:5671 ESTABLISHED
Only the existing already established connection is used, and we can create senders and receivers without paying the overhead of re-initiating the connection all the time. But what if we want to have a dedicated connection for the sender and one for the receiver to improve the throughput?
await using var senderServiceBusClient = new ServiceBusClient(connectionString); await using var receiverServiceBusClient = new ServiceBusClient(connectionString); await using var senderWithDedicatedConnection = senderServiceBusClient.CreateSender(destination); await using var receiverWithDedicatedConnection = receiverServiceBusClient.CreateReceiver(destination); await senderWithDedicatedConnection .SendMessageAsync(new ServiceBusMessage("Deep Dive")); await receiverWithDedicatedConnection.ReceiveMessageAsync();
Let’s consult our good old netstat while the above code is running:
netstat -na | find "5671" TCP 192.168.1.7:59350 184.108.40.206:5671 ESTABLISHED TCP 192.168.1.7:59352 220.127.116.11:5671 ESTABLISHED
Now two dedicated connections are established and the sender and receiver are separated using their TCP connection. Before you jump too early conclusions and think you are going to use the connection sharing approach or always create multiple connections, I suggest you carefully think about usage patterns you are anticipating. Measure it with a realistic load, which makes the most sense for your application or system and then choose the approach which is best for your scenario.
Updated: 2021-03-23 to use the new SDK
[…] Connections […]