/// <summary> /// 消息发送(单个) /// </summary> /// <param name="queueName">队列名称</param> /// <param name="entity">消息数据</param> /// <returns>结果(0失败1成功)</returns> public int SendActiveMQMessage(MessageQueueName queueName, MessageEntity entity) { int msgResult = 0; //消息结果 string msgEntity = ""; //文本消息 //判断是否发送消息 if (entity != null) { try { //创建回话 using (ISession sesssion = connection.CreateSession()) { //实体消息序列化文本消息 msgEntity = JsonConvertTool.SerializeObject(entity); //创建生产者 IDestination destination = new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(queueName.ToString()); IMessageProducer producer = sesssion.CreateProducer(destination); //生产消息 ITextMessage _message = producer.CreateTextMessage(msgEntity); //发送消息(持久化) producer.Send(_message, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.MinValue); } msgResult = 1; } catch (Exception ex) { // LogHelper.WriteLog(typeof(ActiveMq), "方法名:SendActiveMQMessage发送消息队列异常(单个):", Engineer.maq, entity, ex); } } return(msgResult); }
/// <summary> /// 接收消息 /// </summary> private void ReceiveMessage() { //创建工厂 _factory = new ConnectionFactory(MQAddress); //创建连接 _conn = _factory.CreateConnection(); //设置客户端ID _conn.ClientId = Guid.NewGuid().ToString().Replace("_", " ").ToLower(); _conn.Start(); //创建会话 ISession sessions = _conn.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination destination = new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(_MessageQueueName.ToString()); //创建消费者 IMessageConsumer consumer = sessions.CreateConsumer(destination); //异步接收消息 consumer.Listener += new MessageListener(Consumer_Listener); }