Skip to content

Commit

Permalink
Added caching of service bus sender.
Browse files Browse the repository at this point in the history
  • Loading branch information
HansDahle committed Oct 17, 2023
1 parent 54bccd4 commit effc2ae
Showing 1 changed file with 20 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
using System.Text.Json;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using System.Collections.Generic;

namespace Fusion.Resources.ServiceBus
{
internal class ServiceBusQueueSender : IQueueSender
{
private readonly IConfiguration configuration;
private readonly ILogger<ServiceBusQueueSender> logger;
private ServiceBusClient? client;
private readonly ServiceBusClient? client;

// Caching the sender is recommended when the application is publishing messages regularly or semi-regularly. The sender is responsible for ensuring efficient network, CPU, and memory use
private Dictionary<string, ServiceBusSender> cachedSenders = new Dictionary<string, ServiceBusSender>();

public ServiceBusQueueSender(IConfiguration configuration, ILogger<ServiceBusQueueSender> logger)
{
Expand All @@ -36,13 +40,10 @@ public async Task SendMessageDelayedAsync(QueuePath queue, object message, int d
{
if (!IsDisabled)
{
if (client is null)
throw new InvalidOperationException("Service bus has not been configured. Missing connection string.");

var jsonMessage = JsonSerializer.Serialize(message);

var entityPath = ResolveQueuePath(queue);
var queueSender = client.CreateSender(entityPath);
var queueSender = GetQueueSender(entityPath);

var sbMessage = new ServiceBusMessage(jsonMessage) { ContentType = "application/json" };
if (delayInSeconds > 0)
Expand All @@ -57,6 +58,20 @@ public async Task SendMessageDelayedAsync(QueuePath queue, object message, int d
}
}

private ServiceBusSender GetQueueSender(string queue)
{
if (client is null)
throw new InvalidOperationException("Service bus has not been configured. Missing connection string.");

if (cachedSenders.ContainsKey(queue))
{
return cachedSenders[queue];
}

cachedSenders[queue] = client.CreateSender(queue);
return cachedSenders[queue];
}

/// <summary>
/// Queue path should be configured in config. The config key should be the enum value.
///
Expand Down

0 comments on commit effc2ae

Please sign in to comment.