将我的项目从 .Net Framework 4.7 转换为 .Net core 2.1 时,我遇到了 Servicebus MessagingFactory
的问题。我在 .Net core 的新 nuget 包 Microsoft.Azure.ServiceBus
中没有看到任何 MessagingFactory
类。
我的.Net框架4.7代码
private static readonly string messagingConnectionString = Environment.GetEnvironmentVariable("ServiceBusConnection");
private static Lazy<MessagingFactory> lazyMessagingFactory = new Lazy<MessagingFactory>(() =>
{
return MessagingFactory.CreateFromConnectionString(messagingConnectionString);
});
public static MessagingFactory MessagingFactory
{
get
{
return lazyMessagingFactory.Value;
}
}
public static MessagingFactory EventHubMessageFactory
{
get
{
return lazyEventhubMessagingFactory.Value;
}
}
public async Task SendMessageToQueueAsync(string queueName, string message)
{
QueueClient queueClient = MessagingFactory.CreateQueueClient(queueName);
BrokeredMessage brokeredMessage = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(message)), true);
await queueClient.SendAsync(brokeredMessage);
}
这是一个 best practices对于高性能应用程序,我还在单个服务总线命名空间下有许多队列,并且根据配置推送消息。我不想在每个请求中创建 QueueClient
对象,也不想维护每个队列的连接字符串。
.Net Core 中 MessagingFactory
的替代品是什么?
最佳答案
将.NetFramework代码迁移到.Netcore时会发生重大变化,您可以看到Guide for migrating to Azure.Messaging.ServiceBus from Microsoft.Azure.ServiceBus
下面的示例
static void Main(string[] args)
{
string connectionString = "<connection_string>";
string queueName = "<queue_name>";
// since ServiceBusClient implements IAsyncDisposable we create it with "await using"
var client = new ServiceBusClient(connectionString);
// create the sender
ServiceBusSender sender = client.CreateSender(queueName);
for (int i = 0; i < 10; i++)
{
// create a message that we can send. UTF-8 encoding is used when providing a string.
ServiceBusMessage message = new ServiceBusMessage($"Hello world {i}!");
// send the message
sender.SendMessageAsync(message).GetAwaiter().GetResult();
}
sender.DisposeAsync().GetAwaiter().GetResult();
client.DisposeAsync().GetAwaiter().GetResult();
}
关于azure - .Net Core 中 ServiceBus MessagingFactory 的替代品是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60649392/