/// <summary> /// 触发一个事件且将事件打包成消息发送到远程队列中 /// </summary> /// <param name="eventMessage">发送的消息实例</param> /// <param name="exchange">exchange名称</param> /// <param name="queue">队列名称</param> public void TriggerEventMessage(EventMessage eventMessage, string exchange, string queue) { Context.SendConnection = RabbitMqClientFactory.CreateConnection();//获取链接 using (Context.SendConnection) { Context.SendChannel = RabbitMqClientFactory.CreateModel(Context.SendConnection);//获得通道 const byte deliveryMode = 2; using (Context.SendChannel) { var messageSerializer = MessageSerializerFactory.CreateMessageSerializerInstance(); //反序列化消息 var properties = Context.SendChannel.CreateBasicProperties(); properties.DeliveryMode = deliveryMode; //表示持久化消息 //推送消息 Context.SendChannel.BasicPublish(exchange, queue, properties, messageSerializer.SerializerBytes(eventMessage)); } } }
/// <summary> /// 侦听初始化 /// </summary> private void ListenInit() { Context.ListenConnection = RabbitMqClientFactory.CreateConnection(); Context.ListenConnection.ConnectionShutdown += (o, e) => { //todo log 记录日志信息 connection shutdown:e.ReplyText //if (LogLocation.Log.IsNotNull()) // LogLocation.Log.WriteInfo("SCM.RabbitMQClient", "connection shutdown:" + e.ReplyText); }; Context.ListenChannel = RabbitMqClientFactory.CreateModel(Context.ListenConnection); //创建消费者 var consumer = new EventingBasicConsumer(Context.ListenChannel); consumer.Received += Consumer_Recevied; //一次只获取一个消息进行消费 Context.ListenChannel.BasicQos(0, 1, false); Context.ListenChannel.BasicConsume(Context.ListenQueueName, false, consumer); }