Example #1
0
        static void Main(string[] args)
        {
            // Example connection strings:
            //    activemq:tcp://activemqhost:61616
            //    stomp:tcp://activemqhost:61613
            //    ems:tcp://tibcohost:7222
            //    msmq://localhost

            Uri connecturi = new Uri("activemq:tcp://192.168.122.1:36917");

            Console.WriteLine("About to connect to " + connecturi);

            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = session.GetQueue("divisas");
                    Console.WriteLine("Using destination: " + destination);

                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        // Send a message
                        ITextMessage request = session.CreateTextMessage("nombreDivisa:USD|precio:14.30");

                        producer.Send(request);
                    }
                }
        }
Example #2
0
        private static void Main(string[] args)
        {
            Console.WriteLine("ActiveMQ Consumer Demo");

            string topic = "TextQueue";

            string brokerUri             = $"activemq:tcp://192.168.250.198:61616"; // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("artemis", "simetraehcapa"))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(topic))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();
                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                string       body   = txtMsg.Text;

                                Console.WriteLine($"Received message: {txtMsg.Text}");
                            }
                            else
                            {
                                Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                            }
                        }
            }

            Console.WriteLine($"");
            Console.WriteLine($"Press any key to finish.");
            Console.ReadKey(true);
        }
Example #3
0
        private static void Main(string[] args)
        {
            Console.WriteLine("ActiveMQ Producer Demo");

            string topic = "TextQueue";

            Console.WriteLine($"Adding message to queue topic: {topic}");

            string brokerUri             = $"activemq:tcp://192.168.250.198:61616"; // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("artemis", "simetraehcapa"))
            {
                var msg = $"a log message {DateTime.UtcNow}";

                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(topic))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;

                            producer.Send(session.CreateTextMessage(msg));
                            Console.WriteLine($"Sent {msg} messages");
                        }
            }

            Console.WriteLine($"");
            Console.WriteLine($"Press any key to finish.");
            Console.ReadKey(true);
        }
Example #4
0
        private static void SendNewMessage(string text, string host, string password, string user)
        {
            //string topic = "TextQueue";
            string topic = "GPDC-LOGIN";

            // Console.WriteLine($"Adding message to queue topic: {topic}");

            String brokerUri             = "activemq:tcp://" + host + ":" + "61616";
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection(user, password))

            {
                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(topic))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                            producer.Send(session.CreateTextMessage(text));
                            Console.WriteLine($"Sending: {text} ");

                            session.Dispose();
                        }
                if (connection.IsStarted)
                {
                    connection.Close();
                }
            }
        }
        public static String ReadNextMessageQueue2()
        {
            string queueName = "formatedFile";

            string brokerUri             = $"activemq:tcp://localhost:61616";
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();

                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                string       body   = txtMsg.Text;

                                return(body);
                            }
                            else
                            {
                                return("error");
                            }
                        }
            }
        }
Example #6
0
        private void Send(int numberOfMessages)
        {
            IConnectionFactory connectionFactory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(BrokerUri));

            using (IConnection connection = connectionFactory.CreateConnection())
            {
                connection.Start();

                using (ISession session = connection.CreateSession())
                {
                    IQueue queue = session.GetQueue(Queue);

                    using (IMessageProducer producer = session.CreateProducer(queue))
                    {
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        ITextMessage message = producer.CreateTextMessage(TextMessage);

                        for (int i = 0; i < numberOfMessages; i++)
                        {
                            producer.Send(message);
                            Tracer.Debug("Sent message.");
                            sent++;
                        }
                    }
                }
            }
        }
Example #7
0
        private static bool ReadNextMessage()
        {
            const string queueName = "TestTextQueue";

            var brokerUri = $"amqp://*****:*****@localhost:5672";

            var connectionFactory = new NMSConnectionFactory(brokerUri);

            using var connection = connectionFactory.CreateConnection();
            connection.Start();

            using var session     = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            using var destination = session.GetQueue(queueName);
            using var consumer    = session.CreateConsumer(destination);

            var message = consumer.Receive();

            if (message is ITextMessage textMessage)
            {
                Console.WriteLine($"Received message: {textMessage}");

                return(true);
            }

            Console.WriteLine("Unexpected message type: " + message.GetType().Name);
            return(false);
        }
Example #8
0
        private void SendMessageToBackgroundProcess()
        {
            //TODO: this is copid alot. This boiler plate code should be in a common shared class and setup using the same DI setup that the db context goes through.
            Uri connecturi = new Uri("activemq:tcp://activemq:61616");

            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");

                    // Create a consumer and producer
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        // Send a message
                        ITextMessage request = session.CreateTextMessage("Message from actor api service.");

                        producer.Send(request);
                    }
                }
        }
Example #9
0
        /// <summary>
        /// Create the NMS Factory that can create NMS Connections.  This function loads the
        /// connection settings from the configuration file.
        /// </summary>
        /// <param name="nameTestURI">The named connection configuration.</param>
        /// <returns></returns>
        protected bool CreateNMSFactory(string nameTestURI)
        {
            Uri brokerUri = null;

            object[] factoryParams            = null;
            string   connectionConfigFileName = GetConnectionConfigFileName();

            Assert.IsTrue(File.Exists(connectionConfigFileName), "Connection configuration file does not exist.");
            XmlDocument configDoc = new XmlDocument();

            configDoc.Load(connectionConfigFileName);
            XmlElement uriNode = (XmlElement)configDoc.SelectSingleNode(String.Format("/configuration/{0}", nameTestURI));

            if (null != uriNode)
            {
                // Replace any environment variables embedded inside the string.
                brokerUri     = new Uri(ReplaceEnvVar(uriNode.GetAttribute("value")));
                factoryParams = GetFactoryParams(uriNode);
                clientId      = ReplaceEnvVar(GetNodeValueAttribute(uriNode, "clientId", "NMSTestClientId"));
                userName      = ReplaceEnvVar(GetNodeValueAttribute(uriNode, "userName", "guest"));
                passWord      = ReplaceEnvVar(GetNodeValueAttribute(uriNode, "passWord", "guest"));

                if (null == factoryParams)
                {
                    NMSFactory = new Apache.NMS.NMSConnectionFactory(brokerUri);
                }
                else
                {
                    NMSFactory = new Apache.NMS.NMSConnectionFactory(brokerUri, factoryParams);
                }
            }

            return(null != NMSFactory);
        }
Example #10
0
        static void ReadNextMessage()
        {
            while (true)
            {
                string topic = "TextQueue";

                string brokerUri             = $"activemq:tcp://localhost:61616"; // Default port
                NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

                using (IConnection connection = factory.CreateConnection())
                {
                    connection.Start();
                    using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                        using (IDestination dest = session.GetTopic(topic))
                            using (IMessageConsumer consumer = session.CreateConsumer(dest))
                            {
                                IMessage msg = consumer.Receive();
                                if (msg is ITextMessage)
                                {
                                    ITextMessage txtMsg = msg as ITextMessage;
                                    string       body   = txtMsg.Text;


                                    Console.WriteLine($"Messege: {txtMsg.Text}");
                                }
                                else
                                {
                                    Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                                }
                            }
                }
            }
        }
Example #11
0
        static bool ReadNextMessage()
        {
            string queueName = "New";

            string brokerUri             = $"activemq:tcp://localhost:61616";  // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000));

                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                msgList.Add(txtMsg.Text);

                                Console.WriteLine($"Received message: {txtMsg.Text}");

                                return(true);
                            }
                            else
                            {
                                Console.WriteLine("Unexpected message type: ");
                                return(false);
                            }
                        }
            }
        }
Example #12
0
        public static T PullFromActiveMQ(int queueNumber)
        {
            Uri connecturi = new Uri("activemq:tcp://54.173.238.145:61616");

            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = SessionUtil.GetDestination(session, GETQueueName(queueNumber));

                    // Create a consumer and producer
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            // Start the connection so that messages will be processed.
                            connection.Start();
                            producer.DeliveryMode = MsgDeliveryMode.Persistent;

                            // Consume a message
                            ITextMessage message = consumer.Receive() as ITextMessage;
                            if (message == null)
                            {
                                return(default(T));
                            }
                            else
                            {
                                T opld = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(message.Text);

                                return(opld);
                            }
                        }
                }
        }
Example #13
0
        public ActionResult <IEnumerable <string> > Get()
        {
            Uri connecturi = new Uri("activemq:tcp://activemq:61616");

            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");

                    // Create a consumer and producer
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        // Send a message
                        ITextMessage request = session.CreateTextMessage("Message from title api service.");

                        producer.Send(request);
                    }
                }

            return(new string[] { "value1", "value2" });
        }
Example #14
0
        //enviar mensajes al servicio de comunicacion/mensajeria
        public void SendQueueMessages(Player message)
        {
            // definir nombre del queue, en caso de no existir activemq lo crea
            // definir el uri del endpoint de aws mq - aws acepta ssl no tcp asi que el string cambia en el protocolo
            // al ser ssl hay que enviar las credenciales
            // hay que configurar en aws console para que el VPC acepte trafico de afuera, agregar una politica en el security group para inbound traffic
            // connectionfactory del package apache.nms provee manejo de comunicacion con el queue
            // definir el "producer" en caso de la clase que envia de mensaje
            // definir el "receiver" en caso de ser el servicio(s) consumiendo mensajes del queue

            string queueName = "dev_queue";

            Console.WriteLine($"Adding message to queue topic: {queueName}");
            //string brokerUri = $"activemq:tcp://localhost:61616";  // dev broker

            string brokerUri             = $"activemq:ssl://b-92a12260-5d2f-4a73-be53-6c78e22ef8b4-1.mq.us-east-2.amazonaws.com:61617"; //prod broker
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("admin", "adminactivemq"))
            {
                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                            producer.Send(message);
                            Console.WriteLine($"Sent {message} messages");
                        }
            }
        }
Example #15
0
        public object ReadNextObjectMessage(string destination)
        {
            NMSConnectionFactory factory = new NMSConnectionFactory(_brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(destination))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();
                            if (msg is IObjectMessage)
                            {
                                IObjectMessage objMsg = msg as IObjectMessage;
                                var            body   = objMsg.Body;
                                //if (body == "PatientCreated")
                                //{

                                //}
                                //Console.WriteLine($"Received message: {txtMsg.Text}");

                                return(body);
                            }
                            else
                            {
                                //Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                                return("Unexpected message type: " + msg.GetType().Name);
                            }
                        }
            }
        }
Example #16
0
        private static bool ReadNextMessage()
        {
            const string topic = "TestTextTopic";

            var brokerUri = $"activemq:tcp://localhost:61616";

            var connectionFactory = new NMSConnectionFactory(brokerUri);

            using var connection = connectionFactory.CreateConnection("sans-app", "password");
            connection.Start();

            using var session     = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            using var destination = session.GetTopic(topic);
            using var consumer    = session.CreateConsumer(destination);

            var message = consumer.Receive();

            if (message is ITextMessage)
            {
                var textMessage = message as ITextMessage;
                Console.WriteLine($"Received message: {textMessage.Text}");

                return(true);
            }

            Console.WriteLine("Unexpected message type: " + message.GetType().Name);
            return(false);
        }
Example #17
0
        private static void ReceiveMessages()
        {
            try
            {
                IConnectionFactory     factory    = new NMSConnectionFactory(ConfigHelper.GetConfigValueByKey("QueueConnectionString"));
                Apache.NMS.IConnection connection = factory.CreateConnection();
                //"username", "password"
                connection.Start();
                ISession         session          = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IDestination     queueDestination = SessionUtil.GetDestination(session, ConfigHelper.GetConfigValueByKey("QueueName"));
                IMessageConsumer consumer         = session.CreateConsumer(queueDestination);

                consumer.Listener += new MessageListener(Message_Listener);
                Thread.Sleep(Convert.ToInt32(ConfigHelper.GetConfigValueByKey("TimeOut")));
                connection.Close();

                Console.WriteLine("Restart message wait");
            }
            catch (Exception e)
            {
                StreamWriter sw = new StreamWriter("error.txt", true);
                sw.WriteLine("Error==={0}==={1}", DateTime.Now.ToString(), e.ToString());
                sw.Close();
            }
            ReceiveMessages();
        }
		public void TestMaxInactivityDuration()
		{
			string testuri = "activemq:tcp://${activemqhost}:61616" +
										"?wireFormat.maxInactivityDurationInitialDelay=5000" +
										"&wireFormat.maxInactivityDuration=10000" +
										"&connection.asyncClose=false";

			NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));
			using(IConnection connection = factory.CreateConnection("", ""))
			{
				connection.Start();
				using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
				{
					IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME);
					using(IMessageConsumer consumer = session.CreateConsumer(destination))
					using(IMessageProducer producer = session.CreateProducer(destination))
					{
						SendMessage(producer);

						IMessage receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
						Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");

						// Go inactive...
						Thread.Sleep(TimeSpan.FromSeconds(30));

						// Send another message.
						SendMessage(producer);
						receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
						Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");
					}
				}
			}
		}
Example #19
0
        static void Main(string[] args)
        {
            Uri connecturi = new Uri("activemq:tcp://localhost:61616");

            Console.WriteLine("About to connect to " + connecturi);

            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = session.GetDestination("queue://FOO.BAR");
                    connection.Start();
                    Console.WriteLine("Connection established");

                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                        Console.WriteLine("Press enter to send another message, q to quit");
                        while ((Console.ReadLine() ?? "").ToLower() != "q")
                        {
                            var payload = "Hello there. " + DateTime.Now.ToLongTimeString();
                            var message = session.CreateTextMessage(payload);
                            producer.Send(message);
                            Console.WriteLine("Message sent. " + payload);
                            Console.WriteLine("------------------------------------------");
                        }
                    }
                }

            Console.WriteLine("Terminating..");
        }
        /// <summary>
        /// Create the NMS Factory that can create NMS Connections. This
        /// function loads the connection settings from the configuration file.
        /// </summary>
        /// <param name="nameTestURI">The named connection configuration.
        /// </param>
        /// <returns>Connection factory</returns>
        public NMSConnectionFactory CreateNMSFactory(string nameTestURI)
        {
            XmlElement uriNode = GetURINode(nameTestURI);

            Uri brokerUri = null;

            object[] factoryParams = null;
            if (uriNode != null)
            {
                // Replace any environment variables embedded inside the string.
                brokerUri     = new Uri(uriNode.GetAttribute("value"));
                factoryParams = GetFactoryParams(uriNode);
                cnxClientId   = GetNodeValueAttribute(uriNode, "cnxClientId", "NMSTestClientId");
                cnxUserName   = GetNodeValueAttribute(uriNode, "cnxUserName", null);
                cnxPassWord   = GetNodeValueAttribute(uriNode, "cnxPassWord", null);
            }

            if (factoryParams == null)
            {
                this.nmsFactory = new Apache.NMS.NMSConnectionFactory(brokerUri);
            }
            else
            {
                this.nmsFactory = new Apache.NMS.NMSConnectionFactory(brokerUri, factoryParams);
            }

            return(this.nmsFactory);
        }
Example #21
0
        public static void PushToActiveMQ(T opldObject, int queueNumber)
        {
            Uri connecturi = new Uri("activemq:tcp://54.173.238.145:61616");

            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = SessionUtil.GetDestination(session, GETQueueName(queueNumber));

                    // Create the producer
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        var messageToQueue = JsonConvert.SerializeObject(opldObject);

                        //var ss = "Test Message " + DateTime.Now;
                        ITextMessage request = session.CreateTextMessage(messageToQueue);
                        request.NMSCorrelationID = "abc";
                        //request.Properties["NMSXGroupID"] = "cheese";
                        //request.Properties["myHeader"] = "Cheddar";

                        producer.Send(request);
                    }
                }
        }
        public void TestConnectionSendsAuthenticationData()
        {
            NMSConnectionFactory factory = new NMSConnectionFactory("activemq:mock://localhost:61616");

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using (Connection connection = factory.CreateConnection(username, password) as Connection)
            {
                Assert.IsNotNull(connection);

                MockTransport transport = (MockTransport)connection.ITransport.Narrow(typeof(MockTransport));

                transport.OutgoingCommand = new CommandHandler(OnOutgoingCommand);

                connection.Start();

                Thread.Sleep(1000);

                Assert.IsNotNull(this.info);
                Assert.AreEqual(username, info.UserName);
                Assert.AreEqual(password, info.Password);

                connection.Close();
            }
        }
Example #23
0
        private void Upload(PostCardProcessContext postCardUploadContext)
        {
            try
            {
                using (var connection = new NMSConnectionFactory(Hacker.Inko.Global.Properties.Settings.Default.BrokerUrl).CreateConnection())
                {
                    //通过连接创建Session会话
                    using (var session = connection.CreateSession())
                    {
                        //通过会话创建生产者,方法里面new出来的是MQ中的Queue
                        var prod = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("firstQueue"));
                        //创建一个发送的消息对象
                        var message = prod.CreateTextMessage();
                        //给这个对象赋实际的消息
                        message.Text = JsonConvert.SerializeObject(postCardUploadContext.PostCardProcessInfo);
                        //设置消息对象的属性,这个很重要哦,是Queue的过滤条件,也是P2P消息的唯一指定属性
                        message.Properties.SetString("filter", "demo");
                        //生产者把消息发送出去,几个枚举参数MsgDeliveryMode是否长链,MsgPriority消息优先级别,发送最小单位,当然还有其他重载
                        prod.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);
                    }
                }

                postCardUploadContext.Success?.Invoke(postCardUploadContext.PostCardProcessInfo);
            }
            catch (Exception)
            {
                postCardUploadContext.Failure?.Invoke(postCardUploadContext.PostCardProcessInfo);
            }
        }
        public void TestConnection()
        {
            IConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(connectionUri));

            using (connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = SessionUtil.GetDestination(session, "queue://TEST.test.in");
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        Connection amqConnection = connection as Connection;
                        connection.ExceptionListener += ConnectionException;

                        consumer.Listener += OnMessage;

                        TcpFaultyTransport transport = amqConnection.ITransport.Narrow(typeof(TcpFaultyTransport)) as TcpFaultyTransport;
                        Assert.IsNotNull(transport);
                        transport.OnewayCommandPreProcessor += FailOnKeepAlive;

                        Thread.Sleep(TimeSpan.FromSeconds(2));

                        connection.Start();

                        Assert.IsTrue(exceptionOccuredEvent.WaitOne(TimeSpan.FromSeconds(30 * 3)),
                                      "Exception didnt occured within waiting time");
                    }
                }
        }
        public void TestURIForPrefetchHandling(int queuePreFetch, int queueBrowserPrefetch, int topicPrefetch, int durableTopicPrefetch, int maximumPendingMessageLimit)
        {
            string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616" +
                                           "?nms.PrefetchPolicy.queuePrefetch={0}" +
                                           "&nms.PrefetchPolicy.queueBrowserPrefetch={1}" +
                                           "&nms.PrefetchPolicy.topicPrefetch={2}" +
                                           "&nms.PrefetchPolicy.durableTopicPrefetch={3}" +
                                           "&nms.PrefetchPolicy.maximumPendingMessageLimit={4}",
                                           queuePreFetch, queueBrowserPrefetch, topicPrefetch, durableTopicPrefetch, maximumPendingMessageLimit);

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using (IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(queuePreFetch, amqConnection.PrefetchPolicy.QueuePrefetch);
                Assert.AreEqual(queueBrowserPrefetch, amqConnection.PrefetchPolicy.QueueBrowserPrefetch);
                Assert.AreEqual(topicPrefetch, amqConnection.PrefetchPolicy.TopicPrefetch);
                Assert.AreEqual(durableTopicPrefetch, amqConnection.PrefetchPolicy.DurableTopicPrefetch);
                Assert.AreEqual(maximumPendingMessageLimit, amqConnection.PrefetchPolicy.MaximumPendingMessageLimit);

                connection.Close();
            }
        }
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        _logger.LogInformation("CONSUMER running at: {time}", DateTimeOffset.Now);
        _logger.LogInformation($"CONSUMER about to connect to {_options.ConnectUri}");

        var factory = new NMSConnectionFactory(_options.ConnectUri);

        using var connection = factory.CreateConnection();
        using var session    = connection.CreateSession();

        var destination = SessionUtil.GetDestination(session, _options.Destination);

        _logger.LogInformation($"CONSUMER using destination: {destination}");

        using var consumer = session.CreateConsumer(destination);

        connection.Start();

        consumer.Listener += (IMessage message) =>
        {
            _logger.LogInformation($"Received message with ID: {message.NMSMessageId}");
            _logger.LogInformation($"Received message with text: {(message as ITextMessage).Text}");
        };

        ct.WaitHandle.WaitOne();
    }
Example #27
0
        static bool ReadNextMessageQueue()
        {
            string brokerUri             = $"activemq:tcp://{hostIp}:{hostPort}"; // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();
                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                string       body   = txtMsg.Text;
                                Console.WriteLine($"Received message: {txtMsg.Text}");
                                return(true);
                            }
                            else
                            {
                                Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                            }
                        }
            }
            return(false);
        }
Example #28
0
        public void SendQueueMessages(GTMS.Models.Message message)
        {
            // definir nombre del queue, en caso de no existir activemq lo crea
            // definir el uri del endpoint de aw - aws acepta ssl no tcp asi que el string cambia en el protocolo
            // al ser ssl hay que enviar las credenciales
            // apache.nms connectionfactory provee manejo de comunicacion con el queue
            // definir el "producer" en caso de la clase que envia de mensaje
            // definir el "receiver" en caso de ser el servicio consumiendo el queue

            string queueName = "dev_queue";

            Console.WriteLine($"Adding message to queue topic: {queueName}");

            string brokerUri = $"activemq:tcp://localhost:61616";  // dev broker
            //string brokerUri = $"activemq:ssl://b-57e8bf3e-69c9-4bec-b528-de407901bd09-1.mq.us-east-2.amazonaws.com:61617";

            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("admin", "adminactivemq"))
            {
                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                            producer.Send(message);
                            Console.WriteLine($"Sent {message} messages");
                        }
            }
        }
        public void TestMaxInactivityDuration()
        {
            string testuri = "activemq:tcp://${activemqhost}:61616" +
                             "?wireFormat.maxInactivityDurationInitialDelay=5000" +
                             "&wireFormat.maxInactivityDuration=10000" +
                             "&connection.asyncClose=false";

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            using (IConnection connection = factory.CreateConnection("", ""))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            SendMessage(producer);

                            IMessage receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
                            Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");

                            // Go inactive...
                            Thread.Sleep(TimeSpan.FromSeconds(30));

                            // Send another message.
                            SendMessage(producer);
                            receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
                            Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");
                        }
                }
            }
        }
Example #30
0
        static void Main(string[] args)
        {
            var uri = new Uri("activemq:tcp://*****:*****@gmail.com"
                            });
                            producer.Send(msg);
                            Console.WriteLine("Send");
                        }
                    }
                }
        }
Example #31
0
        private void Receive(int numberOfMessages)
        {
            IConnectionFactory connectionFactory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(BrokerUri));

            using (IConnection connection = connectionFactory.CreateConnection())
            {
                connection.Start();

                connection.ConnectionInterruptedListener += OnConnectionInterrupted;
                connection.ConnectionResumedListener     += OnConnectionResumed;

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IQueue queue = session.GetQueue(Queue);

                    using (IMessageConsumer consumer = session.CreateConsumer(queue))
                    {
                        for (int i = 0; i < numberOfMessages; i++)
                        {
                            IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(5000));
                            Assert.IsNotNull(message);
                            Tracer.Debug("Received message.");
                            received++;
                        }
                    }
                }

                connection.ConnectionInterruptedListener -= OnConnectionInterrupted;
                connection.ConnectionResumedListener     -= OnConnectionResumed;
            }
        }
		public void TestURI(string connectionURI)
		{
			NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(connectionURI));
			Assert.IsNotNull(factory);
			Assert.IsNotNull(factory.ConnectionFactory);
			using(IConnection connection = factory.CreateConnection("", ""))
			{
				Assert.IsNotNull(connection);
				connection.Close();
			}
		}
		public void TestInactivityMonitorThreadLeak(
			[Values(0, 1000)]
			int inactivityDuration)
		{
			Process currentProcess = Process.GetCurrentProcess();
			Tracer.InfoFormat("Beginning thread count: {0}, handle count: {1}", currentProcess.Threads.Count, currentProcess.HandleCount);

			string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616?wireFormat.maxInactivityDuration={0}", inactivityDuration);
	
			NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

			// We measure the initial resource counts, and then allow a certain fudge factor for the resources
			// to fluctuate at run-time.  We allow for a certain amount of fluctuation, but if the counts
			// grow outside the safe boundaries of delayed garbage collection, then we fail the test.
			currentProcess = Process.GetCurrentProcess();
			int beginThreadCount = currentProcess.Threads.Count;
			int beginHandleCount = currentProcess.HandleCount;
			int maxThreadGrowth = 10;
			int maxHandleGrowth = 500;

			for(int i = 0; i < 200; i++)
			{
				using(IConnection connection = factory.CreateConnection("ResourceLeakTest", "Password"))
				{
					using(ISession session = connection.CreateSession())
					{
						IDestination destination = SessionUtil.GetDestination(session, "topic://NMSResourceLeak.TestTopic");
						using(IMessageConsumer consumer = session.CreateConsumer(destination))
						{
							connection.Start();
						}
					}
				}

				currentProcess = Process.GetCurrentProcess();
				int endThreadCount = currentProcess.Threads.Count;
				int endHandleCount = currentProcess.HandleCount;

				Assert.Less(endThreadCount, beginThreadCount + maxThreadGrowth, string.Format("Thread count grew beyond maximum of {0} on iteration #{1}.", maxThreadGrowth, i));
				Assert.Less(endHandleCount, beginHandleCount + maxHandleGrowth, string.Format("Handle count grew beyond maximum of {0} on iteration #{1}.", maxHandleGrowth, i));
			}
		}
        public void TestURIForRedeliverPolicyHandling()
        {
            string uri1 = "activemq:tcp://${activemqhost}:61616" +
                          "?nms.RedeliveryPolicy.BackOffMultiplier=10" +
                          "&nms.RedeliveryPolicy.InitialRedeliveryDelay=2000" +
                          "&nms.RedeliveryPolicy.UseExponentialBackOff=true" +
                          "&nms.RedeliveryPolicy.UseCollisionAvoidance=true" +
                          "&nms.RedeliveryPolicy.CollisionAvoidancePercent=20";

            string uri2 = "activemq:tcp://${activemqhost}:61616" +
                          "?nms.RedeliveryPolicy.backOffMultiplier=50" +
                          "&nms.RedeliveryPolicy.initialRedeliveryDelay=4000" +
                          "&nms.RedeliveryPolicy.useExponentialBackOff=false" +
                          "&nms.RedeliveryPolicy.useCollisionAvoidance=false" +
                          "&nms.RedeliveryPolicy.collisionAvoidancePercent=10";

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(uri1));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;

                Assert.AreEqual(10, amqConnection.RedeliveryPolicy.BackOffMultiplier);
                Assert.AreEqual(2000, amqConnection.RedeliveryPolicy.InitialRedeliveryDelay);
                Assert.AreEqual(true, amqConnection.RedeliveryPolicy.UseExponentialBackOff);
                Assert.AreEqual(true, amqConnection.RedeliveryPolicy.UseCollisionAvoidance);
                Assert.AreEqual(20, amqConnection.RedeliveryPolicy.CollisionAvoidancePercent);
            }

            factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(uri2));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(50, amqConnection.RedeliveryPolicy.BackOffMultiplier);
                Assert.AreEqual(4000, amqConnection.RedeliveryPolicy.InitialRedeliveryDelay);
                Assert.AreEqual(false, amqConnection.RedeliveryPolicy.UseExponentialBackOff);
                Assert.AreEqual(false, amqConnection.RedeliveryPolicy.UseCollisionAvoidance);
                Assert.AreEqual(10, amqConnection.RedeliveryPolicy.CollisionAvoidancePercent);
            }
        }
        public void TestURIForPrefetchHandlingOfAll(int allPreFetch)
        {
            string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616" +
                          				   "?nms.PrefetchPolicy.all={0}", allPreFetch);

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.QueuePrefetch);
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.QueueBrowserPrefetch);
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.TopicPrefetch);
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.DurableTopicPrefetch);

				connection.Close();
			}
        }		
        public void TestURIForPrefetchHandling(int queuePreFetch, int queueBrowserPrefetch, int topicPrefetch, int durableTopicPrefetch, int maximumPendingMessageLimit)
        {
            string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616" +
                          				   "?nms.PrefetchPolicy.queuePrefetch={0}" +
                                           "&nms.PrefetchPolicy.queueBrowserPrefetch={1}" +
                                           "&nms.PrefetchPolicy.topicPrefetch={2}" +
                                           "&nms.PrefetchPolicy.durableTopicPrefetch={3}" +
                                           "&nms.PrefetchPolicy.maximumPendingMessageLimit={4}",
			                               queuePreFetch, queueBrowserPrefetch, topicPrefetch, durableTopicPrefetch, maximumPendingMessageLimit);

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(queuePreFetch, amqConnection.PrefetchPolicy.QueuePrefetch);
                Assert.AreEqual(queueBrowserPrefetch, amqConnection.PrefetchPolicy.QueueBrowserPrefetch);
                Assert.AreEqual(topicPrefetch, amqConnection.PrefetchPolicy.TopicPrefetch);
                Assert.AreEqual(durableTopicPrefetch, amqConnection.PrefetchPolicy.DurableTopicPrefetch);
                Assert.AreEqual(maximumPendingMessageLimit, amqConnection.PrefetchPolicy.MaximumPendingMessageLimit);

				connection.Close();
			}
        }
Example #37
0
        /// <summary>
        /// Create the NMS Factory that can create NMS Connections.  This function loads the
        /// connection settings from the configuration file.
        /// </summary>
        /// <param name="nameTestURI">The named connection configuration.</param>
        /// <returns></returns>
        protected bool CreateNMSFactory(string nameTestURI)
        {
            Uri brokerUri = null;
            string[] paths = GetConfigSearchPaths();
            object[] factoryParams = null;
            string connectionConfigFileName = GetConnectionConfigFileName();
            bool configFound = false;

            foreach(string path in paths)
            {
                string fullpath = Path.Combine(path, connectionConfigFileName);
                Tracer.Debug("\tScanning folder: " + path);

                if(File.Exists(fullpath))
                {
                    Tracer.Debug("\tAssembly found!");
                    connectionConfigFileName = fullpath;
                    configFound = true;
                    break;
                }
            }

            Assert.IsTrue(configFound, "Connection configuration file does not exist.");
            XmlDocument configDoc = new XmlDocument();

            configDoc.Load(connectionConfigFileName);
            XmlElement uriNode = (XmlElement) configDoc.SelectSingleNode(String.Format("/configuration/{0}", nameTestURI));

            if(null != uriNode)
            {
                // Replace any environment variables embedded inside the string.
                brokerUri = new Uri(ReplaceEnvVar(uriNode.GetAttribute("value")));
                factoryParams = GetFactoryParams(uriNode);
                clientId = ReplaceEnvVar(GetNodeValueAttribute(uriNode, "clientId", "NMSTestClientId"));
                userName = ReplaceEnvVar(GetNodeValueAttribute(uriNode, "userName", "guest"));
                passWord = ReplaceEnvVar(GetNodeValueAttribute(uriNode, "passWord", "guest"));
            }

            if(null == factoryParams)
            {
                NMSFactory = new Apache.NMS.NMSConnectionFactory(brokerUri);
            }
            else
            {
                NMSFactory = new Apache.NMS.NMSConnectionFactory(brokerUri, factoryParams);
            }

            return (null != NMSFactory);
        }
        public void TestConnectionSendsAuthenticationData()
        {
            NMSConnectionFactory factory = new NMSConnectionFactory("activemq:mock://localhost:61616");
            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(Connection connection = factory.CreateConnection(username, password) as Connection)
            {
                Assert.IsNotNull(connection);

				MockTransport transport = (MockTransport) connection.ITransport.Narrow(typeof(MockTransport));

                transport.OutgoingCommand = new CommandHandler(OnOutgoingCommand);

                connection.Start();

                Thread.Sleep(1000);
                
                Assert.IsNotNull(this.info);
                Assert.AreEqual(username, info.UserName);
                Assert.AreEqual(password, info.Password);
				
				connection.Close();
            }
        }