예제 #1
0
        public virtual void Publish <T>(T message) where T : IMessage
        {
            var descriptor = _messageTopicResolver.Resolve(message);

            var headers = _coreSessionProvider.Session.ToHeaders();

            if (headers != null)
            {
                var rich = new RichMessageDescriptor(descriptor.MessageGroup, descriptor.MessageTopic);
                foreach (var item in headers)
                {
                    rich.Headers.Add(item.Key, item.Value);
                }
                descriptor = rich;
            }

            if (_messageStore.IsPublishedAsync(descriptor, message).GetAwaiter().GetResult())
            {
                _logger.LogWarning($"[{descriptor.MessageGroup}][{descriptor.MessageTopic}]Message has already published");
                return;
            }
            var wrapper = new MessageWrapper(descriptor, message);

            _messagePublisherWrapper.Publish(wrapper);
            _messageStore.StoreAsync(descriptor, message).GetAwaiter().GetResult();
        }
예제 #2
0
        private async Task ConsumerMessageReceived(object sender, BasicDeliverEventArgs eventArgs)
        {
            var consumer   = sender as IBasicConsumer;
            var descriptor = new RichMessageDescriptor(eventArgs.Body,
                                                       eventArgs.Exchange, eventArgs.RoutingKey, eventArgs.Redelivered, eventArgs.BasicProperties?.ContentEncoding, eventArgs.BasicProperties?.ContentType, eventArgs.BasicProperties?.MessageId, eventArgs.BasicProperties?.Persistent, eventArgs.BasicProperties?.Headers);

            try
            {
                await ProcessMessageAsync(descriptor, eventArgs.Body);

                Logger.LogInformation($"处理消息成功, 即将Ack, Consumer: {eventArgs.ConsumerTag} Exchange: {descriptor.MessageGroup}, RoutingKey: {descriptor.MessageTopic}, Redelivered: {descriptor.Redelivered}");
                consumer.Model.BasicAck(eventArgs.DeliveryTag, multiple: false);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"处理消息出错, 即将Nack并设置reueue为true, Consumer: {eventArgs.ConsumerTag} Exchange: {descriptor.MessageGroup}, RoutingKey: {descriptor.MessageTopic}, Redelivered: {descriptor.Redelivered}");
                consumer.Model.BasicNack(eventArgs.DeliveryTag, multiple: false, true);
            }
        }