feat: finalize core modules and gateway
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using RabbitMQ.Client;
|
||||
using TakeoutSaaS.Module.Messaging.Abstractions;
|
||||
using TakeoutSaaS.Module.Messaging.Options;
|
||||
using TakeoutSaaS.Module.Messaging.Serialization;
|
||||
|
||||
namespace TakeoutSaaS.Module.Messaging.Services;
|
||||
|
||||
/// <summary>
|
||||
/// RabbitMQ 消息发布实现。
|
||||
/// </summary>
|
||||
public sealed class RabbitMqMessagePublisher(RabbitMqConnectionFactory connectionFactory, IOptionsMonitor<RabbitMqOptions> optionsMonitor, JsonMessageSerializer serializer, ILogger<RabbitMqMessagePublisher> logger)
|
||||
: IMessagePublisher, IAsyncDisposable
|
||||
{
|
||||
private IConnection? _connection;
|
||||
private IModel? _channel;
|
||||
private bool _disposed;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task PublishAsync<T>(string routingKey, T message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
EnsureChannel();
|
||||
var options = optionsMonitor.CurrentValue;
|
||||
|
||||
_channel!.ExchangeDeclare(options.Exchange, options.ExchangeType, durable: true, autoDelete: false);
|
||||
var body = serializer.Serialize(message);
|
||||
var props = _channel.CreateBasicProperties();
|
||||
props.ContentType = "application/json";
|
||||
props.DeliveryMode = 2;
|
||||
props.MessageId = Guid.NewGuid().ToString("N");
|
||||
|
||||
_channel.BasicPublish(options.Exchange, routingKey, props, body);
|
||||
logger.LogDebug("发布消息到交换机 {Exchange} RoutingKey {RoutingKey}", options.Exchange, routingKey);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void EnsureChannel()
|
||||
{
|
||||
if (_channel != null && _channel.IsOpen)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_connection ??= connectionFactory.CreateConnection();
|
||||
_channel = _connection.CreateModel();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放 RabbitMQ 资源。
|
||||
/// </summary>
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_channel?.Dispose();
|
||||
_connection?.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user