chore: 升级依赖并优化种子
This commit is contained in:
@@ -14,41 +14,42 @@ public sealed class RabbitMqMessagePublisher(RabbitMqConnectionFactory connectio
|
||||
: IMessagePublisher, IAsyncDisposable
|
||||
{
|
||||
private IConnection? _connection;
|
||||
private IModel? _channel;
|
||||
private IChannel? _channel;
|
||||
private bool _disposed;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task PublishAsync<T>(string routingKey, T message, CancellationToken cancellationToken = default)
|
||||
public async Task PublishAsync<T>(string routingKey, T message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 确保通道可用
|
||||
EnsureChannel();
|
||||
await EnsureChannelAsync(cancellationToken);
|
||||
var options = optionsMonitor.CurrentValue;
|
||||
|
||||
var channel = _channel ?? throw new InvalidOperationException("RabbitMQ channel is not available.");
|
||||
// 2. 声明交换机
|
||||
channel.ExchangeDeclare(options.Exchange, options.ExchangeType, durable: true, autoDelete: false);
|
||||
await channel.ExchangeDeclareAsync(options.Exchange, options.ExchangeType, durable: true, autoDelete: false, cancellationToken: cancellationToken);
|
||||
// 3. 序列化消息并设置属性
|
||||
var body = serializer.Serialize(message);
|
||||
var props = channel.CreateBasicProperties();
|
||||
props.ContentType = "application/json";
|
||||
props.DeliveryMode = 2;
|
||||
props.MessageId = Guid.NewGuid().ToString("N");
|
||||
var props = new BasicProperties
|
||||
{
|
||||
ContentType = "application/json",
|
||||
DeliveryMode = DeliveryModes.Persistent,
|
||||
MessageId = Guid.NewGuid().ToString("N")
|
||||
};
|
||||
|
||||
// 4. 发布消息
|
||||
channel.BasicPublish(options.Exchange, routingKey, props, body);
|
||||
await channel.BasicPublishAsync(options.Exchange, routingKey, mandatory: false, props, body, cancellationToken);
|
||||
logger.LogDebug("发布消息到交换机 {Exchange} RoutingKey {RoutingKey}", options.Exchange, routingKey);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void EnsureChannel()
|
||||
private async Task EnsureChannelAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_channel != null && _channel.IsOpen)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_connection ??= connectionFactory.CreateConnection();
|
||||
_channel = _connection.CreateModel();
|
||||
_connection ??= await connectionFactory.CreateConnectionAsync(cancellationToken);
|
||||
_channel = await _connection.CreateChannelAsync(cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in New Issue
Block a user