async Task IMessagePublisher.PublishAsync <T>(string key, T model, CancellationToken cancellationToken) { var options = new ConsumeOption <T>(); this.rabbitMqProducer.SendMessage(exchange: ConstConfig.ExchangeName, routeKey: options.QueueName, model); await Task.CompletedTask; }
public RabbitMqConsumerBase(IServiceProvider provider, ILogger logger, IConnection connection, ISerializeProvider _serializer, ConsumeOption option) { provider.Should().NotBeNull(); logger.Should().NotBeNull(); connection.Should().NotBeNull(); _serializer.Should().NotBeNull(); option.Should().NotBeNull(); this.provider = provider; this.logger = logger; this._serializer = _serializer; this._option = option; this._option.Valid(); this._channel = connection.CreateModel(); //qos if (this._option.ConcurrencySize != null) { this._channel.BasicQos(prefetchSize: 0, prefetchCount: this._option.ConcurrencySize.Value, global: false); } //异步消费 this._consumer = new AsyncEventingBasicConsumer(this._channel); //注册消费事件 this._consumer.Received += async(sender, args) => { using var s = this.provider.CreateScope(); try { var res = await this.OnMessageReceived(new ConsumerMessage <T>(this._serializer, args)); if (!res) { throw new MsgException("未能消费"); } if (!this._option.AutoAck) { this._channel.BasicAck(args.DeliveryTag, multiple: true); } } catch (Exception e) { //log errors this.logger.AddErrorLog($"rabbitmq消费发生异常:{e.Message}", e); if (!this._option.AutoAck) { this._channel.BasicNack(args.DeliveryTag, multiple: true, requeue: true); } } }; }
public RabbitMqConsumerBase(IServiceProvider provider, ILogger logger, IConnection connection, ConsumeOption option) { provider.Should().NotBeNull(); logger.Should().NotBeNull(); connection.Should().NotBeNull(); option.Should().NotBeNull(); this.provider = provider; this.logger = logger; this._option = option; this._serializer = provider.ResolveSerializer(); this._channel = connection.CreateModel(); //qos if (this._option.ConcurrencySize != null) { this._channel.BasicQos(prefetchSize: 0, prefetchCount: this._option.ConcurrencySize.Value, global: false); } //异步消费 this._consumer = new AsyncEventingBasicConsumer(this._channel); //注册消费事件 this._consumer.Received += async(sender, args) => { using var s = this.provider.CreateScope(); var body = this.__deserialize__(args.Body.ToArray()); if (body == null) { return; } var context = new BasicMessageConsumeContext <T>(body); if (!this._option.AutoAck) { context.AckHandler = async(success) => { if (success) { this._channel.BasicAck(args.DeliveryTag, multiple: true); } else { this._channel.BasicNack(args.DeliveryTag, multiple: true, requeue: true); } await Task.CompletedTask; }; } try { await this.OnMessageReceived(context); await context.Ack(true); } catch (Exception e) { //log errors this.logger.AddErrorLog($"rabbitmq消费发生异常:{e.Message}", e); await context.Ack(false); } }; }