public Task PublishAsync(Type messageType, object message) { AssertUtils.IsNotNull(message, "消息不能null"); var topic = GetTopic(messageType); var wrapMessage = new RabbitMessageBusData { Type = topic, Data = _options.Serializer.Serialize(message), ExecuteTimeStamp = DateUtils.GetTimeStamp(DateTime.Now) }; var data = _options.Serializer.Serialize(wrapMessage); this._producer.ProduceAsync(topic, data); return(Task.CompletedTask); }
public async Task PublishDelayAsync(Type messageType, object message, TimeSpan delay) { AssertUtils.IsNotNull(message, "消息不能null"); if (delay > TimeSpan.Zero) { //加入延迟队列 var topic = GetTopic(messageType); var wrapMessage = new RabbitMessageBusData { Type = topic, Data = _options.Serializer.Serialize(message), ExecuteTimeStamp = DateUtils.GetTimeStamp(DateTime.Now.Add(delay)) }; var data = _options.Serializer.Serialize(wrapMessage); this._producer.ProduceDelayAsync(topic, data, delay); } else { await this.PublishAsync(messageType, message); } }
/// <summary> /// 执行消费事件 /// </summary> /// <param name="obj"></param> /// <returns></returns> private async Task <bool> Handler(RabbitMessageBusData obj) { var isSuccess = true; //失败标识需要重试 if (OnMessage == null) { return(isSuccess); } try { isSuccess = await OnMessage(obj); } catch (Exception ex) { _logger.LogError(ex, $"rabbitMQ消费失败, topic={obj.Type},group={_groupId}"); isSuccess = false; } return(isSuccess); }
/// <summary> /// 加入延迟队列重试 /// </summary> /// <param name="data"></param> private void ExecuteErrorToDelayTask(RabbitMessageBusData data) { if (data.ErrorCount < _options.MaxErrorReTryCount) { var delay = TimeSpan.FromSeconds(GetDelaySecond(data.ErrorCount)); data.ErrorCount++; data.ErrorGroupId = _groupId; data.ExecuteTimeStamp = DateUtils.GetTimeStamp(DateTime.Now.Add(delay)); var delayData = _options.Serializer.Serialize(data); if (delay > TimeSpan.Zero) { _producer.ProduceDelayAsync(data.Type, delayData, delay); } else //立即重试的情况 { _producer.ErrorReProduceAsync(data.Type, data.ErrorGroupId, delayData); } } }