gpt4 book ai didi

azure - 将消息放入队列的代码(可能)有问题

转载 作者:行者123 更新时间:2023-12-03 06:58:44 28 4
gpt4 key购买 nike

我有这段代码将消息放入队列

 public class AzureQueueService : IAzureQueueService
{
private readonly IConfiguration _config;
private static string azureServiceBusString = null;

public AzureQueueService(IConfiguration config)
{
_config = config;
azureServiceBusString = "connString";
}

public async Task SendMessageAsync<T>(T serviceBusMessage, string queueName)
{
// since ServiceBusClient implements IAsyncDisposable we create it with "await using"
await using var queueClient = new ServiceBusClient(azureServiceBusString);

// create the sender
ServiceBusSender sender = queueClient.CreateSender(queueName);

string messageBody = JsonSerializer.Serialize(serviceBusMessage);
var message = new ServiceBusMessage(Encoding.UTF8.GetBytes(messageBody));

// send the message
await sender.SendMessageAsync(message);
}
}

在我的启动文件中我正在这样做

services.AddTransient<IAzureQueueService, Core.Services.AzureQueueService>();

我就是这样使用的

var queue = new AzureQueueService(config);
await queue.SendMessageAsync(message, "emailqueue");

这会导致内存泄漏吗?我的意思是我应该在构造函数中实例化 ServiceBusClient 吗?

最佳答案

是的,我希望为 ServiceBusClient 设置依赖项注入(inject)。根据docs here (对于 7.8.x)

The ServiceBusClient, senders, receivers, and processors are safe to cache and use as a singleton for the lifetime of the application, which is best practice when messages are being sent or received regularly. They are responsible for efficient management of network, CPU, and memory use, working to keep usage low during periods of inactivity.

另请参阅Best Practises for performance improvements using Service Bus Messaging

关于azure - 将消息放入队列的代码(可能)有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72655962/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com