.net core 7.0 实现向service bus发送数据,再从service bus读取数据并写入Azure sql中
- 创建一个 .NET Core 7.0 应用程序,并添加以下 NuGet 包:
- Microsoft.Azure.ServiceBus
- Microsoft.Azure.ServiceBus.Core
- Microsoft.Azure.ServiceBus.Processor
- Microsoft.Data.SqlClient
-
在 Azure 门户中创建一个 Service Bus,并记录下连接字符串和队列名称。
-
在 Azure 门户中创建一个 Azure SQL 数据库,并记录下连接字符串和表名称。
-
创建一个类来处理 Service Bus 的发送和接收:
using Microsoft.Azure.ServiceBus;
using System;
using System.Text;
using System.Threading.Tasks;
public class ServiceBusHandler
{
private readonly IQueueClient _queueClient;
public ServiceBusHandler(string connectionString, string queueName)
{
_queueClient = new QueueClient(connectionString, queueName);
}
public async Task SendMessageAsync(string message)
{
var body = Encoding.UTF8.GetBytes(message);
var messageObj = new Message(body);
await _queueClient.SendAsync(messageObj);
}
public async Task<string> ReceiveMessageAsync()
{
var message = await _queueClient.ReceiveAsync();
if (message != null)
{
var body = Encoding.UTF8.GetString(message.Body);
await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
return body;
}
return null;
}
}
- 创建一个类来处理 Azure SQL 数据库的写入:
using Microsoft.Data.SqlClient;
using System.Threading.Tasks;
public class SqlHandler
{
private readonly string _connectionString;
private readonly string _tableName;
public SqlHandler(string connectionString, string tableName)
{
_connectionString = connectionString;
_tableName = tableName;
}
public async Task WriteToSqlAsync(string message)
{
using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
var command = new SqlCommand($"INSERT INTO {_tableName} (Message) VALUES (@Message)", connection);
command.Parameters.AddWithValue("@Message", message);
await command.ExecuteNonQueryAsync();
}
}
- 在程序入口处创建实例并调用:
public static async Task Main(string[] args)
{
var serviceBusHandler = new ServiceBusHandler("ConnectionString", "QueueName");
var sqlHandler = new SqlHandler("ConnectionString", "TableName");
await serviceBusHandler.SendMessageAsync("Hello from Service Bus!");
var message = await serviceBusHandler.ReceiveMessageAsync();
if (message != null)
{
await sqlHandler.WriteToSqlAsync(message);
}
}
以上代码将向 Service Bus 发送一条消息,然后从 Service Bus 接收一条消息,并将其写入 Azure SQL 数据库。可以根据实际情况进行调整和优化。
原文地址: http://www.cveoy.top/t/topic/tKx 著作权归作者所有。请勿转载和采集!