//客户端发送消息的时候要标记上消息的持久化状态 //可以在创建队列的时候设置此队列是持久化的,但是队列中的消息要在我们发送某个消息的时候打上需要持久化的状态标记。 public void TriggerEventMessage() { //Context.SendConnection = RabbitMQClientFactory.CreateConnectionForSend();//获取连接 Context.SendConnection = RabbitMQClientFactory.CreateConnection(Context.MqConfigDom);//获取连接 using (Context.SendConnection) { //获取发送通道 Context.SendChannel = RabbitMQClientFactory.CreateModel(Context.SendConnection); //声明消息队列 Context.SendChannel.QueueDeclare(Context.SendQueueName, true, false, false, null); //交换机 Context.SendChannel.ExchangeDeclare(Context.SendExchange, Context.RoutType, true, false, null); //绑定 Context.SendChannel.QueueBind(Context.SendQueueName, Context.SendExchange, Context.RoutKey); using (Context.SendChannel) { //序列化消息器 var messageSerializer = MessageSerializerFactory.CreateMessageSerializerInstance(); //消息持久化 var properties = Context.SendChannel.CreateBasicProperties(); properties.DeliveryMode = Message.deliveryMode; //推送消息 byte[] sMessage = messageSerializer.SerializerBytes(Message); Console.WriteLine(string.Format("发送信息:{0}", Newtonsoft.Json.JsonConvert.SerializeObject(Message.MessageEntity))); Context.SendChannel.BasicPublish(Context.SendExchange, Context.SendQueueName, properties, sMessage); } } }
private void ListenInit() { try { //获取连接 lock (this) { //Context.ListenConnection = RabbitMQClientFactory.CreateConnectionForSumer(); Context.ListenConnection = RabbitMQClientFactory.CreateConnection(Context.MqConfigDom); //获取通道 Context.ListenChannel = RabbitMQClientFactory.CreateModel(Context.ListenConnection); //获取消息队列中有多少消息数量。 //int count = Convert.ToInt32(Context.ListenChannel.MessageCount(Context.ListenQueueName)); //创建事件驱动的消费者模型 //QueueingBasicConsumer这个是队列的消费者 var consumer = new EventingBasicConsumer(Context.ListenChannel); consumer.Received += Consumer_Received; //即在非自动确认消息的前提下,如果一定数目的消息(通过基于consume或者channel设置Qos的值)未被确认前,不进行消费新的消息。 // void BasicQos(uint prefetchSize, ushort prefetchCount, bool global); /*prefetchSize:0 * prefetchCount:会告诉RabbitMQ不要同时给一个消费者推送多于N个消息,即一旦有N个消息还没有ack,则该consumer将block掉,直到有消息ack * global:true\false 是否将上面设置应用于channel,简单点说,就是上面限制是channel级别的还是consumer级别,如果是false就是当前channel */ Context.ListenChannel.BasicQos(0, 1, false); //消息确认, 首先将autoAck自动确认关闭,等我们的任务执行完成之后,手动的去确认 //Context.ListenChannel.BasicConsume(Context.ListenQueueName, false, consumer); Context.ListenChannel.BasicConsume(Context.ListenQueueName, false, consumer.ConsumerTag != null? consumer.ConsumerTag:"tag", false, false, null, consumer); } } catch (Exception ex) { if (LogLocation.Log != null) { LogLocation.Log.WriteInfo("RabbitMQClient", "ListenInit()方法报错:" + ex.Message); } } }