public MessageConsumerBase(ConnectionFactory factory, SettingConfig config) { this._config = config ?? throw new ArgumentException(nameof(config)); this._connection = factory.CreateConnection(); this._connection.ConnectionShutdown += (sender, args) => { }; this._connection.ConnectionBlocked += (sender, args) => { }; this._connection.ConnectionUnblocked += (sender, args) => { }; this._channel = this._connection.CreateModel(); this._channel.BasicSetting(this._config); this._consumer = new EventingBasicConsumer(this._channel); this._consumer.Received += async(sender, args) => { try { //重试策略 var retryPolicy = Policy.Handle <Exception>().WaitAndRetryAsync( retryCount: (int)this._config.ConsumeRetryCount, sleepDurationProvider: i => TimeSpan.FromMilliseconds(this._config.ConsumeRetryWaitMilliseconds)); await retryPolicy.ExecuteAsync(async() => { var result = await this.OnMessageReceived(sender, args); if (result == null || !result.Value) { throw new Exception("未能消费对象"); } //do nothing await FakeAsync(); }); } catch (Exception e) { //log errors e.AddErrorLog(); } finally { if (this._config.Ack) { //从队列中移除消息 this._channel.X_BasicAck(args); } } }; var consumerTag = $"{Environment.MachineName}|{this._config.QueueName}|{this._config.ConsumerName}"; this._channel.BasicConsume( queue: this._config.QueueName, noAck: !this._config.Ack, consumerTag: consumerTag, consumer: this._consumer); }
/// <summary> /// 基本设置 /// </summary> public static void BasicSetting(this IModel channel, SettingConfig config) { channel.X_ExchangeDeclare(config.ExchangeName, config.ExchangeType, config.Delay); if (!ValidateHelper.IsPlumpString(config.QueueName)) { throw new ArgumentException(nameof(config.QueueName)); } channel.X_QueueBind(config.QueueName, config.ExchangeName, config.RouteKey, config.Args); //每个消费一次收到多少消息,其余的放在队列里 channel.BasicQos(0, 1, false); }