public void Scribe(IMessageConsumer consumer)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException(nameof(consumer));
            }
            if (string.IsNullOrWhiteSpace(consumer.Topic))
            {
                throw new Exception($"{consumer.GetType()} topic为空");
            }
            if (consumer.Type != ConsumerType.Subscribe)
            {
                throw new Exception($"{consumer.GetType()} 不是subscribe模式的消费者");
            }

            if (!_consumers.ContainsKey(consumer.Topic))
            {
                _consumers.Add(consumer.Topic, new List <IMessageConsumer>()
                {
                    consumer
                });
            }
            else
            {
                _consumers[consumer.Topic].Add(consumer);
            }
        }
        public void Register <T>(IMessageConsumer <T> consumer)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException();
            }

            var type = consumer.GetType().GetInterfaces().FirstOrDefault()?.GenericTypeArguments.FirstOrDefault();

            if (type == null)
            {
                throw new ArgumentNullException();
            }

            var queue   = type.Name;
            var channel = _connection.CreateModel();

            Declare(channel, queue);

            var eventConsumer = new EventingBasicConsumer(channel);

            eventConsumer.Received += (model, ea) =>
            {
                var content = Encoding.UTF8.GetString(ea.Body);
                T   obj     = JsonSerializer.Deserialize <T>(content);
                consumer.Receive(obj);
            };

            channel.BasicConsume(queue: queue,
                                 autoAck: true,
                                 consumer: eventConsumer);
        }
        public void Subscribe(IMessageConsumer consumer)
        {
            _consumerType = consumer.GetType();
            var attr       = _consumerType.GetCustomAttribute <MessageHandlerAttribute>(inherit: true);
            var exchange   = attr.Exchange;
            var routingKey = attr.RoutingKey;
            var queueName  = $"{exchange}.{routingKey}";

            _channel.ExchangeDeclare(exchange,
                                     ExchangeType.Direct,
                                     true,
                                     false,
                                     new Dictionary <string, object>()
            {
                { "x-message-ttl", 0 }
            });
            _channel.QueueDeclare(queueName,
                                  durable: true,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);
            _channel.QueueBind(queueName, exchange, routingKey);
            _channel.BasicQos(0, 10, false);

            var basicConsumer = new EventingBasicConsumer(_channel);

            basicConsumer.Received += async(sender, e) =>
            {
                var body    = e.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                try
                {
                    using var scope = _serviceScopeFactory.CreateScope();
                    var consumers = scope.ServiceProvider.GetServices <IMessageConsumer>()
                                    .Where(x => x.GetType() == _consumerType).ToList();

                    consumers.ForEach(async consumer => {
                        var handleResult = await consumer.ConsumeAsync(message);
                    });

                    _channel.BasicAck(e.DeliveryTag, true);
                }
                catch (Exception exception)
                {
                    _logger.Fatal(nameof(Subscribe), exception);
                    throw;
                }
            };

            _channel.BasicConsume(queueName, false, basicConsumer);
        }
        private async Task SaftyProcess(IMessageConsumer consumer, string key, string message)
        {
            if (consumer.IgnoreKey(key))
            {
                return;
            }

            using (var scope = _serviceProvider.CreateScope())
            {
                var sessionContext = scope.ServiceProvider.GetRequiredService <IDapperSessionContext>();
                try
                {
                    await consumer.Handler(scope, key, message);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"{consumer.GetType()} 消费消息出错,{consumer.Topic}-{key}-{message}");
                    sessionContext.Cancel();
                }
            }
        }
 public Type[] GetMessagesConsumed(IMessageConsumer consumer)
 {
     Type consumerType = consumer.GetType();
     return GetMessagesConsumed(consumerType, type => false);
 }
Exemple #6
0
        public Type[] GetMessagesConsumed(IMessageConsumer consumer)
        {
            Type consumerType = consumer.GetType();

            return(GetMessagesConsumed(consumerType, type => false));
        }
Exemple #7
0
        /// <summary>
        /// Registers the message consumer.
        /// </summary>
        /// <param name="consumer">Consumer.</param>
        public void RegisterMessageConsumer (IMessageConsumer consumer)
        {
            Logger.Log.AddLogEntry(LogLevel.Fine, ClassName, "Registering new message consumer '{0}'",
                consumer.GetType().ToString());

            DeferredRegisters.Enqueue (() => consumer.ValidMessages.ForEach (i =>
                {
                    List<IMessageConsumer> tmp;
                    if (MessageList.TryGetValue(i, out tmp))
                        tmp.Add(consumer);
                    else
                    {
                        tmp = new List<IMessageConsumer>(consumer.ToCollection());
                        MessageList[i] = tmp;
                    }
                })
            );
        }
Exemple #8
0
        /// <summary>
        /// Unregisters the message consumer.
        /// </summary>
        /// <param name="consumer">Consumer.</param>
        public void UnregisterMessageConsumer(IMessageConsumer consumer)
        {
            Logger.Log.AddLogEntry(LogLevel.Fine, ClassName, "Removing message consumer '{0}'",
                consumer.GetType().ToString());

            DeferredUnregisters.Enqueue(() => consumer.ValidMessages.ForEach(i =>
                {
                    List<IMessageConsumer> tmp;
                    if (MessageList.TryGetValue(i, out tmp))
                    {
                        tmp.Remove(consumer);
                    }
                })
            );
        }