RabbitMQ 发送消息时,如何绑定customer 的一个回调方法用于消息接收?

jvhmr 2017-11-01 02:58:04
IModel channel = connection.CreateModel();
channel.QueueDeclare("Queue.Test", true, false, false, null);
channel.BasicQos(0, 1, false);
var customer = new QueueingBasicConsumer(channel);
channel.BasicConsume("Queue.Test", false, customer);

--------------------------------------------------------------------------------------------------------

也就是不用单独启动一个customer 客户端来接收消息
...全文
573 2 打赏 收藏 举报
写回复
2 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
        
public static void CosumeMessage<T>(IConnection conn, string exchangeName, string exchangeType, string queueName, bool durable, bool autoDelete, bool exclusive, string routingKey, Action<T> action)
        {
            IModel channel = conn.CreateModel();
            bool noAck = false;

            channel.ExchangeDeclare(exchangeName, exchangeType, durable, autoDelete, null);
            channel.QueueDeclare(queueName, durable, autoDelete, exclusive, arguments: null);
            channel.QueueBind(queueName, exchangeName, routingKey, null);
            channel.BasicQos(0, 1, false);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (ch, ea) =>
            {
                try
                {
                    var body = ea.Body;
                    IBasicProperties props = ea.BasicProperties;
                    string message = Encoding.UTF8.GetString(body);
                    T tmp = message.FromJsv<T>();
                    if (action != null)
                    {
                        action(tmp);
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                    }
                    else
                    {
                        channel.BasicReject(deliveryTag: ea.DeliveryTag, requeue: true);
                    }
                }
                catch (Exception e)
                {
                    channel.BasicReject(deliveryTag: ea.DeliveryTag, requeue: true);
                    LogUtil.WriteWorkflowLog("Cosume failed", e);
                }

            };
            channel.BasicConsume(queueName, noAck, consumer);
        }
  • 打赏
  • 举报
回复
jvhmr 2017-11-02
自己up一下
  • 打赏
  • 举报
回复
相关推荐
发帖
C#

10.8w+

社区成员

.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
帖子事件
创建了帖子
2017-11-01 02:58
社区公告

让您成为最强悍的C#开发者