c#MQ简单操作

来源:互联网 发布:计算机视觉常用算法 编辑:程序博客网 时间:2024/05/18 03:35

利用HESSIAN序列化自定义实体,并接收ACTIVEMQ的信息
 这几天因为项目上的需要,需要推送一定的统计信息到WINFROM的项目上。我们利用了ACTIVEMQ进行了推送。因为要和JAVA之间进行数据的推送。里面还是有点意思的。就简单的说一下c#建立ACTIVEMQ,和JAVA之间进行数据的交换。主要有如下几步;

第一步:从网上下载到ACTIVEMQ在.NET中要引用的两个DLL,分别是:Apache.NMS.ActiveMQ.dll,Apache.NMS.dll。网上有下载的地方。你也可以到官网上进行下载。如果有兴趣的话你可以下载代码进行查看。

第二步:自定义实体,这个就不说了,大家都很熟悉。利用定义了一个实体PushMsg;(注意:c#的实体的命名空间必须和JAVA里实体的命名空间保持一致,在实体的头上加上  [Serializable])

第三步:编写ACTIVEMQ的消费者与生产者代码。里面提供了两种方式,TOPIC与Queue。部分代码如下
 public class MQ
    {
        #region 结构与属性的定义

        private string URI;
        private string TOPIC;
        private IConnectionFactory factory;
        private IConnection connection;
        private ISession session;
        private IMessageProducer producer;
        IMessageConsumer imessConsumer = null;


        public string uri
        {
            set { URI = value; }
            get { return URI; }
        }

        public string topic
        {
            set { TOPIC = value; }
            get { return TOPIC; }
        }

        public MQ()
        {
            producer = null;
            factory = null;
            connection = null;
            session = null;
        }

        ~MQ()
        {
            if (producer != null)
            {
                producer.Dispose();
            }

            Close();
        }
        #endregion

        #region 关闭与打开MQ
        public void Start()
        {
            try
            {
                factory = new ConnectionFactory(URI);
                connection = factory.CreateConnection();
                session = connection.CreateSession();
            }
            catch (Exception exp)
            {
                ShitongExceptions.ShowMsg("Start", "MQ", exp.ToString(), "连接MQ有误", "温馨提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, false, true);
            }
        }

        public void Close()
        {
            try
            {
                if (session != null)
                {
                    session.Close();
                }
                if (connection != null)
                {
                    connection.Stop();
                    connection.Close();
                }
            }
            catch (Exception exp)
            {
                ShitongExceptions.ShowMsg("Close", "MQ", exp.ToString(), "关闭MQ有误", "温馨提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, false, true);
            }
        }
        #endregion

        #region 创建生成者与消费者
        /// <summary>
        /// 创建生成者
        /// </summary>
        /// <param name="blnTopic">是否是TOPIC</param>
        /// <param name="strTopicName">TOPIC名称</param>
        public void CreateProducer(bool blnTopic, string strTopicName)
        {
            if (blnTopic)
            {
                producer = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(strTopicName));
                connection.Start();
            }
            else
            {
                producer = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(strTopicName));
                connection.Start();
            }
        }

        public void CreateProducer(bool blnTopic)
        {
            if (blnTopic)
            {
                producer = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(TOPIC));
                connection.Start();
            }
            else
            {
                producer = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(TOPIC));
                connection.Start();
            }
        }

        public IMessageConsumer CreateConsumer(bool blnTopic, string strTopicName)
        {

            if (blnTopic)
            {
                imessConsumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(strTopicName));
                imessConsumer.Listener += new MessageListener(consumer_Listener);
                connection.Start();
            }
            else
            {
                imessConsumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(strTopicName));
                imessConsumer.Listener += new MessageListener(consumer_Listener);
                connection.Start();
            }
            return imessConsumer;
        }

        public IMessageConsumer CreateConsumer(bool blnTopic, string strTopicName, string strSelector)
        {

            if (strSelector == "")
            {
                ShitongExceptions.ShowMsg("IMessageConsumer", "MQ", "MQ selector不能为空", "关闭MQ有误", "温馨提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, false, true);
                return null;
            }
            if (blnTopic)
            {
                imessConsumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(strTopicName), strSelector, false);
                imessConsumer.Listener += new MessageListener(consumer_Listener);
            }
            else
            {
                imessConsumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(strTopicName), strSelector, false);
                imessConsumer.Listener += new MessageListener(consumer_Listener);

            }
            return imessConsumer;
        }
        #endregion

    
        //通过代理发送消息给客户端,客户端接收到消息后调用WPF的图形进行绘图
        public delegate void SendmsgDelegate(PushMsg msg);//定义一个委托        
        public static event SendmsgDelegate SendmsgEvent;

        /// <summary>
        /// 消费者经行监听,获取到监听数据
        /// </summary>
        /// <param name="message"></param>
        private void consumer_Listener(IMessage message)
        {
            try
            {
                IBytesMessage mess = (IBytesMessage)message;
                byte[] by = new byte[mess.BodyLength];
                mess.ReadBytes(by);
                object obj = deserialize(by);
                PushMsg msg=(PushMsg)obj;
                if (SendmsgEvent != null)
                {
                    SendmsgEvent(msg);
                }
            }
            catch (System.Exception e)
            {
                ShitongExceptions.ShowMsg("consumer_Listener", "MQ", e.Message, "MQ监听", "温馨提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, false, true);
            }
        }
        #endregion

    

第四步:序列化与反序列化

 
    #region 序列化与反序列化
     
        //序列化
        public byte[] serialize(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            System.IO.MemoryStream _memory = new System.IO.MemoryStream();
            CHessianOutput hessionot = new CHessianOutput(_memory);
            hessionot.WriteObject(obj);
            return _memory.ToArray();
        }
        //反序列化
        public Object deserialize(byte[] by)
        {
            if (by == null)
            {
                return null;
            }
            System.IO.MemoryStream _memory = new System.IO.MemoryStream(by);
            CHessianInput hessionInput = new CHessianInput(_memory);
            return hessionInput.ReadObject();
        }
        #endregion
    }
第五步:发送数据
 
    #region 发送消息
        public void SendMQMessage(string strText)
        {
            IBytesMessage createBytesMessage = session.CreateBytesMessage();
            byte[] by = serialize(strText);
            createBytesMessage.WriteBytes(by);
            producer.Send(createBytesMessage, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);
        }
        public void SendMQMessage(PushMsg lstProperty)
        {
            try
            {
                IBytesMessage createBytesMessage = session.CreateBytesMessage();
                byte[] by = serialize(lstProperty);
                createBytesMessage.WriteBytes(by);
                producer.Send(createBytesMessage, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);
            }
            catch (System.Exception ex)
            {
                ShitongExceptions.ShowMsg("SendMQMessage", "MQ", ex.Message, "MQ发送信息有误", "温馨提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, false, true);
            }
        }
第六步:监听接收数据
   /// <summary>
        /// 消费者经行监听,获取到监听数据
        /// </summary>
        /// <param name="message"></param>
        private void consumer_Listener(IMessage message)
        {
            try
            {
                IBytesMessage mess = (IBytesMessage)message;
                byte[] by = new byte[mess.BodyLength];
                mess.ReadBytes(by);
                object obj = deserialize(by);
                PushMsg msg=(PushMsg)obj;
                if (SendmsgEvent != null)
                {
                    SendmsgEvent(msg);
                }
            }
            catch (System.Exception e)
            {
                ShitongExceptions.ShowMsg("consumer_Listener", "MQ", e.Message, "MQ监听", "温馨提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, false, true);
            }
        }
其中发送的时候把你的实体装换为BYTE[],然后进行推送。从JAVA接收到的信息通过反序列化 装换为自己的实体。
代码如下:
从JAVA接收到的信息通过反序列化 装换为自己的实体
  IBytesMessage mess = (IBytesMessage)message;
                byte[] by = new byte[mess.BodyLength];
                mess.ReadBytes(by);
                object obj = deserialize(by);
                PushMsg msg=(PushMsg)obj; 
你的实体装换为BYTE[]
  IBytesMessage createBytesMessage = session.CreateBytesMessage();
                byte[] by = serialize(lstProperty);
                createBytesMessage.WriteBytes(by);
 忘了给自己介绍Hessiancsharp.dll,你可以从网上下载一个就行了。在序列化与反序列化的代码中用到。

7断线重连,你在配置连接的URL的时候你配置上failover:URL就行了


0 0
原创粉丝点击