Ejemplo n.º 1
0
 /// <summary>
 /// 添加消费端
 /// </summary>
 /// <param name="register"></param>
 public void AddConsumer <IConsumer>(IConsumerQueueConfig consumerQueueConfig) where IConsumer : IBaseConsumer
 {
     ConsumerOptions.Add(new ConsumerOptions
     {
         ConsumerQueueConfig = consumerQueueConfig,
         ConsumerType        = typeof(IConsumer)
     });
 }
Ejemplo n.º 2
0
        public MQResult DirectConsume(IConsumerQueueConfig config, Func <string, Task <bool> > func)
        {
            try
            {
                RabbitConsumeConfig mqconfig = config as RabbitConsumeConfig;

                var channel = mqConnection.CreateModel();

                #region 声明队列
                try
                {
                    channel.QueueDeclarePassive(mqconfig.QueueName);
                }
                catch
                {
                    channel = mqConnection.CreateModel();
                    channel.QueueDeclare(queue: mqconfig.QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
                }
                #endregion

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += async(model, ea) =>
                {
                    var message = Encoding.UTF8.GetString(ea.Body);
                    var bSucess = await func(message);

                    if (bSucess && !mqconfig.AutoAck)
                    {
                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                    Console.WriteLine($"[C] consumer_message,queue={mqconfig.QueueName},msg={message}");
                };
                channel.BasicQos(0, 1, false);
                channel.BasicConsume(queue: mqconfig.QueueName, autoAck: mqconfig.AutoAck, consumer: consumer);

                return(new MQResult()
                {
                    IsSucess = true, ChannelNumber = channel.ChannelNumber
                });
            }
            catch (Exception ex)
            {
                //记log
                return(new MQResult()
                {
                    IsSucess = false, ExceptionMsg = ex.Message
                });
            }
        }