vs2022 .net core 7.0 实现向service bus发送数据,再从service bus读取数据并写入Azure sql中(代碼整潔)
下面是一个示例代码,它演示了如何使用 VS2022 和 .NET Core 7.0 向 Azure Service Bus 发送数据,然后从 Service Bus 读取数据并将其写入 Azure SQL 数据库中。
using System;
using System.Text;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using Microsoft.Data.SqlClient;
namespace ServiceBusDemo
{
class Program
{
static async Task Main(string[] args)
{
// Azure Service Bus 配置信息
string connectionString = "<connection-string>";
string queueName = "<queue-name>";
// Azure SQL 数据库配置信息
string sqlConnectionString = "<sql-connection-string>";
// 创建 Service Bus 客户端和消息接收器
await using var client = new ServiceBusClient(connectionString);
var receiver = client.CreateReceiver(queueName);
// 创建 SQL 数据库连接并准备 SQL 语句
await using var connection = new SqlConnection(sqlConnectionString);
await connection.OpenAsync();
const string insertSql = "INSERT INTO MyTable (Message) VALUES (@message)";
// 循环接收 Service Bus 消息并将其写入 Azure SQL 数据库
while (true)
{
// 接收消息
ServiceBusReceivedMessage message = await receiver.ReceiveMessageAsync();
// 如果没有收到消息,则退出循环
if (message == null) break;
// 将消息转换为字符串
string messageBody = Encoding.UTF8.GetString(message.Body);
// 将消息写入 Azure SQL 数据库
await using var command = new SqlCommand(insertSql, connection);
command.Parameters.AddWithValue("@message", messageBody);
await command.ExecuteNonQueryAsync();
// 标记消息为已处理
await receiver.CompleteMessageAsync(message);
}
// 关闭连接和 Service Bus 客户端
await connection.CloseAsync();
await client.DisposeAsync();
}
}
}
上面的代码使用 Azure.Messaging.ServiceBus 命名空间中的 ServiceBusClient 和 ServiceBusReceiver 类来接收来自 Service Bus 的消息。它还使用 Microsoft.Data.SqlClient 命名空间中的 SqlConnection 和 SqlCommand 类来连接和写入 Azure SQL 数据库。
在循环中,我们不断接收 Service Bus 消息,并将其写入 Azure SQL 数据库中。我们还使用 receiver.CompleteMessageAsync 方法将已处理的消息标记为已完成。最后,我们在循环结束后关闭连接和 Service Bus 客户端。
请注意,上面的代码只是一个示例,并且需要根据您的具体需求进行修改。特别是,您需要将 <connection-string>、<queue-name> 和 <sql-connection-string> 替换为您自己的值。
原文地址: https://www.cveoy.top/t/topic/tOm 著作权归作者所有。请勿转载和采集!