ActiveMq C#客户端 消息队列的使用(存和取)

时间:2022-06-22 05:44:55

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

using Apache.NMS;

using Apache.NMS.ActiveMQ;

 

namespace NmsProducerClasses

{

    public class MyActiveMq

    {

        private IConnectionFactory factory;

        private IConnection connection;

        private ISession session;

        private IMessageProducer prod;

        private IMessageConsumer consumer;

        private ITextMessage msg;

 

        private bool isTopic = false;

        private bool hasSelector = false;

        private const string ClientID = "clientid";

        private const string Selector = "filter=‘demo‘";

        private bool sendSuccess = true;

        private bool receiveSuccess = true;

 

        public MyActiveMq(bool isLocalMachine, string remoteAddress)

        {

            try

            {

                //初始化工厂  

                if (isLocalMachine)

                {

                    factory = new ConnectionFactory("tcp://localhost:61616/");

                }

                else

                {

                    factory = new ConnectionFactory("tcp://" + remoteAddress + ":61616/"); //写tcp://192.168.1.111:61616的形式连接其他服务器上的ActiveMQ服务器          

                }

                //通过工厂建立连接

                connection = factory.CreateConnection();

                connection.ClientId = ClientID;

                connection.Start();

                //通过连接创建Session会话

                session = connection.CreateSession();

            }

            catch (System.Exception e)

            {

                sendSuccess = false;

                receiveSuccess = false;

                Console.WriteLine("Exception:{0}", e.Message);

                Console.ReadLine();

                throw e;

            }

            Console.WriteLine("Begin connection...");

        }

 

 

        ~MyActiveMq()

        {

            //this.ShutDown();

        }

 

        /// <summary>

        /// 初始化

        /// </summary>

        ///<param>选择是否是Topic

        ///<param>队列名

        ///<param>是否设置过滤

        public bool InitQueueOrTopic(bool topic, string name, bool selector = false)

        {

            try

            {

                //通过会话创建生产者、消费者

                if (topic)

                {