升级依赖并适配消息模块

This commit is contained in:
2025-12-27 11:04:11 +08:00
parent 7e130c7ae0
commit b31a4ea909
23 changed files with 124 additions and 64 deletions

View File

@@ -14,7 +14,7 @@ public sealed class RabbitMqMessagePublisher(RabbitMqConnectionFactory connectio
: IMessagePublisher, IAsyncDisposable
{
private IConnection? _connection;
private IModel? _channel;
private IChannel? _channel;
private bool _disposed;
/// <inheritdoc />
@@ -26,16 +26,16 @@ public sealed class RabbitMqMessagePublisher(RabbitMqConnectionFactory connectio
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, arguments: null, noWait: false, cancellationToken).ConfigureAwait(false);
// 3. 序列化消息并设置属性
var body = serializer.Serialize(message);
var props = channel.CreateBasicProperties();
var props = new BasicProperties();
props.ContentType = "application/json";
props.DeliveryMode = 2;
props.DeliveryMode = DeliveryModes.Persistent;
props.MessageId = Guid.NewGuid().ToString("N");
// 4. 发布消息
channel.BasicPublish(options.Exchange, routingKey, mandatory: false, basicProperties: props, body: body);
await channel.BasicPublishAsync(options.Exchange, routingKey, mandatory: false, basicProperties: props, body: body, cancellationToken).ConfigureAwait(false);
logger.LogDebug("发布消息到交换机 {Exchange} RoutingKey {RoutingKey}", options.Exchange, routingKey);
}
@@ -46,8 +46,8 @@ public sealed class RabbitMqMessagePublisher(RabbitMqConnectionFactory connectio
return;
}
_connection ??= await connectionFactory.CreateConnectionAsync(cancellationToken);
_channel = _connection.CreateModel();
_connection ??= await connectionFactory.CreateConnectionAsync(cancellationToken).ConfigureAwait(false);
_channel = await _connection.CreateChannelAsync(new CreateChannelOptions(false, false, null, null), cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -61,8 +61,19 @@ public sealed class RabbitMqMessagePublisher(RabbitMqConnectionFactory connectio
}
_disposed = true;
_channel?.Dispose();
_connection?.Dispose();
return ValueTask.CompletedTask;
return CloseAsync();
}
private async ValueTask CloseAsync()
{
if (_channel != null)
{
await _channel.CloseAsync(CancellationToken.None).ConfigureAwait(false);
}
if (_connection != null)
{
await _connection.CloseAsync(CancellationToken.None).ConfigureAwait(false);
}
}
}