Represents a connection with a message broker
Inheritance: IConnectionFactory
        private void init(string host, int port)
        {
            ReceivedNumber = 0;
              isFinished = false;
              ReceivedMessages = new List<string>();
              ListionTopics = new List<string>();

              Uri uriSample = new Uri("activemq:tcp://" + host + ":" + port);
              ConnectionFactory confSample = new ConnectionFactory(uriSample);
              connection = (Connection)confSample.CreateConnection();
              connection.Start();
              session = (Session)connection.CreateSession();
        }
Ejemplo n.º 2
3
 public static void SendMessage(string Body)
 {
     try
     {
         //Create the Connection Factory
         IConnectionFactory factory = new ConnectionFactory(queueUrl);
         using (IConnection connection = factory.CreateConnection())
         {
             //Create the Session
             using (ISession session = connection.CreateSession())
             {
                 IMessageProducer prod = session.CreateProducer(
                     new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(queueNm));
                 ITextMessage msg = prod.CreateTextMessage();
                 msg.Text = Body;
                 msg.NMSDeliveryMode = MsgDeliveryMode.Persistent;
                 prod.Send(msg);
             }
         }
     }
     catch (System.Exception e)
     {
         throw e;
     }
 }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            var activeMQConnection = new ConnectionFactory("tcp://localhost:61616");
            //var nmsTemplate = new NmsTemplate(activeMQConnection);
            //nmsTemplate.DefaultDestination = new ActiveMQQueue("mathias");

            var myDtoListener = new MyDtoMessageListener();
            myDtoListener.OnNewMessage += new EventHandler<MyDtoEventArgs>(myDtoListener_OnNewMessage);

            var listener = new SimpleMessageListenerContainer();
            listener.ConnectionFactory = activeMQConnection;
            listener.Destination = new ActiveMQQueue("mathias");
            listener.MessageListener = myDtoListener;
            listener.Initialize();

            // WCF (.Net 3)
            var client = new localhost.MyServiceClient();
            // .Net 2
            //localhost.MyServiceImplService client = new localhost.MyServiceImplService();
            var result = client.test();
            Console.WriteLine(String.Join(" - ", result.data2d[0].ToArray()));

            Console.WriteLine("Press a key to exit");
            Console.ReadKey(true);
        }
Ejemplo n.º 4
0
        public override void Init()
        {
            base.Init();
            _producers = new LinkedList<IMessageProducer>();
            _consumers = new Hashtable();

            XmlNode nmsNode = this.DestinationDefinition.PropertiesXml.SelectSingleNode("nms");
            _nmsSettings = new NMSSettings(nmsNode);
            if (_nmsSettings != null)
            {
                ConnectionFactory connectionFactory = new ConnectionFactory(_nmsSettings.URI);

                log.Debug(string.Format("NMSAdapter Connected to URI {0}", _nmsSettings.URI));

                _connection = connectionFactory.CreateConnection();
                _connection.Start();
                _session = _connection.CreateSession(AcknowledgementMode.DupsOkAcknowledge);

                if (_nmsSettings.DESTINATION_TYPE.StartsWith(NMSSettings.QueueDestination))
                {
                    _destination = new ActiveMQQueue(_nmsSettings.Destination);
                    log.Debug(string.Format("NMSAdapter Connected to Queue {0}", _nmsSettings.Destination));
                }
                else if (_nmsSettings.DESTINATION_TYPE.StartsWith(NMSSettings.TopicDestination))
                {
                    _destination = new ActiveMQTopic(_nmsSettings.Destination);
                    log.Debug(string.Format("NMSAdapter Connected to Topic {0}", _nmsSettings.Destination));
                }
                else
                {
                    log.Debug(string.Format("Unknown Destination Type {0}", _nmsSettings.DESTINATION_TYPE));
                }
            }
        }
        /// <summary>
        /// 实现启动MQ连接方法
        /// </summary>
        public void StartMQ()
        {
            lock (sync)
            {
                try
                {
                    //不重复启动
                    if (IsRuning())
                        return;

                    //创建MQ连接
                    string address = string.Format("failover:(tcp://{0})?randomize=false", this.config.Address);
                    ConnectionFactory connectionFactory = new ConnectionFactory(address);

                    connection = connectionFactory.CreateConnection();

                    connection.ExceptionListener += new ExceptionListener(OnConnectionException);
                    connection.ConnectionInterruptedListener += new ConnectionInterruptedListener(OnConnectionInterrupted);
                    connection.ConnectionResumedListener += new ConnectionResumedListener(OnConnectionResumed);

                    //判断connection状态,连接connection
                    if (!connection.IsStarted)
                        connection.Start();
                    this.stopEvent.Reset();
                    StartMsgProcessThread();
                    this.logHelper.LogInfoMsg("MQConsumer启动成功,Address={0}", this.config.Address);
                }
                catch (Exception ex)
                {
                    this.logHelper.LogErrMsg(ex, "MQConsumer启动异常,Address={0}", this.config.Address);
                    throw ex;
                }
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            try
            {
                ConnectionFactory connectionFactoryTest = new ConnectionFactory(URI);

                using (SimpleMessageListenerContainer listenerTest = new SimpleMessageListenerContainer())
                {
                    listenerTest.ConnectionFactory = connectionFactoryTest;
                    listenerTest.DestinationName = queueName;
                    listenerTest.MessageListener = new ListenerTest();
                    listenerTest.AfterPropertiesSet();
                    listenerTest.Start();

                    Console.WriteLine("Listening to Queue.");
                    Console.WriteLine("[Main]: Press <ENTER> to exit.");
                    Console.Read();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine("[Exception]: Press <ENTER> to exit.");
                Console.Read();
            }
        }
        static void Main(string[] args)
        {
            try
            {
                ConnectionFactory connectionFactory = new ConnectionFactory(URI);
                connectionFactory.UserName = USER;
                connectionFactory.Password = PASS;

                using (SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer())
                {
                    listenerContainer.ConnectionFactory = connectionFactory;
                    listenerContainer.DestinationName = DESTINATION;
                    listenerContainer.MessageListener = new Listener();
                    listenerContainer.AfterPropertiesSet();
                    Console.WriteLine("Listener started.");
                    Console.WriteLine("Press <ENTER> to exit.");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine("Press <ENTER> to exit.");
                Console.Read();
            }
            // comment when testing
            Console.ReadLine();
        }
Ejemplo n.º 8
0
        public void IsertActiveQueue(string  didiStr)
        {
            try
            {
                //Create the Connection Factory
                IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");
                string msg = "";
                using (IConnection connection = factory.CreateConnection())
                {
                    //Create the Session
                    using (ISession session = connection.CreateSession())
                    {
                        //Create the Producer for the topic/queue
                        IMessageProducer prod = session.CreateProducer(
                            //new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("DidiMQ"));
                            new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("DidiMQ"));

                        msg = didiStr;

                        //Send Messages
                        prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);
                    }
                }
                log.Info("Send MQ msg :{0}", msg);
            }
            catch (System.Exception e)
            {
                log.Info("Send MQ error :{0}", e.Message);
            }
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            //初始化工厂,这里默认的URL是不需要修改的
            IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");

            //通过工厂建立连接
            using (IConnection connection = factory.CreateConnection())
            {
                //通过连接创建Session会话
                using (ISession session = connection.CreateSession())
                {
                    //通过会话创建生产者,方法里面new出来的是MQ中的Queue
                    IMessageProducer prod = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("firstQueue"));
                    for (int i = 0; i < 10000; i++)
                    {
                        //创建一个发送的消息对象
                        ITextMessage message = prod.CreateTextMessage();
                        message.Text = "msg-" + i;
                        //设置消息对象的属性,这个很重要哦,是Queue的过滤条件,也是P2P消息的唯一指定属性
                        message.Properties.SetString("filter", "demo");
                        //生产者把消息发送出去,几个枚举参数MsgDeliveryMode是否长链,MsgPriority消息优先级别,发送最小单位,当然还有其他重载
                        prod.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);
                        Console.WriteLine("发送成功!! - {0}", i);
                    }
                }
            }

            Console.ReadKey();
        }
Ejemplo n.º 10
0
        public void Login(String name)
        {
            Uri connecturi = new Uri("failover:tcp://mq.checkmywwstats.com:61616");

            Trace.TraceInformation("About to connect to " + connecturi);
            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);

            _connection = factory.CreateConnection();
            _session    = _connection.CreateSession();
            // Examples for getting a destination:
            //
            // Hard coded destinations:
            //    IDestination destination = session.GetQueue("FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //    IDestination destination = session.GetTopic("FOO.BAR");
            //    Debug.Assert(destination is ITopic);
            //
            // Embedded destination type in the name:
            //    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //    IDestination destination = SessionUtil.GetDestination(session, "topic://FOO.BAR");
            //    Debug.Assert(destination is ITopic);
            //
            // Defaults to queue if type is not specified:
            //    IDestination destination = SessionUtil.GetDestination(session, "FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //
            // .NET 3.5 Supports Extension methods for a simplified syntax:
            //    IDestination destination = session.GetDestination("queue://FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //    IDestination destination = session.GetDestination("topic://FOO.BAR");
            //    Debug.Assert(destination is ITopic);
            //_readQueue = _session.CreateTemporaryQueue();
            DoLogin(name);
            IDestination destination = SessionUtil.GetDestination(_session, "queue://fennecfox.pleasereadlobby");

            Trace.TraceInformation("Using destination: " + destination);
            _lobbyRequestsQueue = _session.CreateConsumer(destination);

            destination          = SessionUtil.GetDestination(_session, "queue://fennecfox.pleasereadthread");
            _threadRequestsQueue = _session.CreateConsumer(destination);

            destination = SessionUtil.GetDestination(_session, "queue://fennecfox.posts");
            _postsQueue = _session.CreateProducer(destination);

            destination = SessionUtil.GetDestination(_session, "queue://fennecfox.lobby");
            _lobbyQueue = _session.CreateProducer(destination);
            _lobbyQueue.DeliveryMode = MsgDeliveryMode.NonPersistent;

            // Start the connection so that messages will be processed.
            _connection.Start();
            _postsQueue.DeliveryMode   = MsgDeliveryMode.NonPersistent;
            _postsQueue.RequestTimeout = receiveTimeout;
            _lobbyQueue.DeliveryMode   = MsgDeliveryMode.NonPersistent;
            _lobbyQueue.RequestTimeout = receiveTimeout;

            _lobbyRequestsQueue.Listener  += new MessageListener(OnLobbyMessage);
            _threadRequestsQueue.Listener += new MessageListener(OnThreadMessage);
        }
Ejemplo n.º 11
0
        protected bool Connecting()
        {
            if (mqConn != null)
            {
                return true;
            }

            // 尝试连接是否成功(不断开自动重连)
            if (!TryConnect())
            {
                return false;
            }

            // 实际连接,断开会自动重连
            string address = GetAddress();
            try
            {
                IConnectionFactory factory = new ConnectionFactory(address);
                mqConn = factory.CreateConnection();
                mqConn.Start();
                mqSession = mqConn.CreateSession(AcknowledgementMode.AutoAcknowledge);
                return true;
            }
            catch (Exception ex)
            {
                ex.ToString();
                return false;
            }
        }
Ejemplo n.º 12
0
        static void Main()
        {
            using (var broker = new EmbeddedBroker())
            {
                Console.WriteLine("{0} Started", DateTime.Now);

                Console.WriteLine("Client connecting to: {0}", broker.FailoverUri);

                ConnectionFactory connectionFactory = new ConnectionFactory(broker.FailoverUri);

                var connection = connectionFactory.CreateConnection();

                connection.Start();

                var session = connection.CreateSession();

                var consumer = session.CreateConsumer(Topic);

                consumer.Listener += message =>
                {
                    var msg = (ActiveMQTextMessage)message;
                    Console.WriteLine("{0} Received: {1}", DateTime.Now, msg.Text);
                };

                var producer = session.CreateProducer(Topic);

                Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(i =>
                {
                    var msg = producer.CreateTextMessage("Message #" + i);
                    producer.Send(msg);
                });

                Console.ReadKey();
            }
        }
Ejemplo n.º 13
0
        public static ArrayList ReceiveMessage()
        {
            ArrayList alText = new ArrayList();
            try
            {
                //Create the Connection Factory
                IConnectionFactory factory = new ConnectionFactory(queueUrl);
                using (IConnection connection = factory.CreateConnection())
                {
                    //Create the Session
                    connection.Start();
                    using (ISession session = connection.CreateSession())
                    {
                        IDestination destination = session.GetQueue(queueNm);

                        using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        {
                            IMessage advisory;
                            while ((advisory = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null)
                            {
                                ActiveMQTextMessage amqMsg = (ActiveMQTextMessage)advisory;
                                alText.Add(amqMsg.Text);
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            return alText;
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            //Create the Connection Factory  
            IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");
            using (IConnection connection = factory.CreateConnection())
            {
                //Create the Session  
                using (ISession session = connection.CreateSession())
                {
                    //Create the Producer for the topic/queue  
                    IMessageProducer prod = session.CreateProducer(
                        new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"));

                    //Send Messages  
                    int i = 0;

                    while (!Console.KeyAvailable)
                    {
                        ITextMessage msg = prod.CreateTextMessage();
                        msg.Text = i.ToString();
                        Console.WriteLine("Sending: " + i.ToString());
                        prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);

                        System.Threading.Thread.Sleep(5000);
                        i++;
                    }
                }
            }

            Console.ReadLine();
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            try
            {
                //Create the Connection factory
                IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");

                //Create the connection
                using (IConnection connection = factory.CreateConnection())
                {
                    connection.ClientId = "testing listener";
                    connection.Start();

                    //Create the Session
                    using (ISession session = connection.CreateSession())
                    {
                        //Create the Consumer
                        IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"), "testing listener", null, false);

                        consumer.Listener += new MessageListener(consumer_Listener);

                        Console.ReadLine();
                    }
                    connection.Stop();
                    connection.Close();
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 16
0
        public void start()
        {
            Console.WriteLine("Starting up Listener.");

            String user        = env("ACTIVEMQ_USER", "admin");
            String password    = env("ACTIVEMQ_PASSWORD", "password");
            String host        = env("ACTIVEMQ_HOST", "localhost");
            int    port        = Int32.Parse(env("ACTIVEMQ_PORT", "61616"));
            String destination = "Info_Transport";
            //arg(args, 0, "Info_Transport");

            String brokerUri = "activemq:tcp://" + host + ":" + port + "?transport.useLogging=true";
            Uri    uri       = new Uri(brokerUri);

            //NMSConnectionFactory factory = new NMSConnectionFactory(uri);
            IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(uri);

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

            connection.Start();
            ISession     session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            IDestination dest    = session.GetTopic(destination);

            IMessageConsumer consumer = session.CreateConsumer(dest);
            DateTime         start    = DateTime.Now;
            long             count    = 0;

            Console.WriteLine("Waiting for messages...");

            while (true)
            {
                try
                {
                    IMessage msg = consumer.Receive();
                    if (msg is ITextMessage)
                    {
                        ITextMessage txtMsg = msg as ITextMessage;
                        String       body   = txtMsg.Text;
                        Console.WriteLine("Message " + body);
                        if (eventMsg != null)
                        {
                            eventMsg(this, msg);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception ..." + ex.Message);
                }
            }
            Console.WriteLine("Shutting down Listener.");
            connection.Close();
        }
Ejemplo n.º 17
0
		public void TestURI(string connectionURI)
		{
			{
				Uri uri = URISupport.CreateCompatibleUri(NMSTestSupport.ReplaceEnvVar(connectionURI));
				ConnectionFactory factory = new ConnectionFactory(uri);
				Assert.IsNotNull(factory);
				using(IConnection connection = factory.CreateConnection("", ""))
				{
					Assert.IsNotNull(connection);
					
					using(ISession session = connection.CreateSession())
					{
						IDestination destination = session.CreateTemporaryTopic();
						using(IMessageProducer producer = session.CreateProducer(destination))
						{
							producer.Close();
						}
						
						using(IMessageConsumer consumer = session.CreateConsumer(destination))
						{
							consumer.Close();
						}
						
						session.Close();
					}
					
					connection.Close();
				}
			}

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

					using(ISession session = connection.CreateSession())
					{
						IDestination destination = session.CreateTemporaryTopic();
						using(IMessageProducer producer = session.CreateProducer(destination))
						{
							producer.Close();
						}
						
						using(IMessageConsumer consumer = session.CreateConsumer(destination))
						{
							consumer.Close();
						}
						
						session.Close();
					}
					
					connection.Close();
				}
			}
		}		
Ejemplo n.º 18
0
        public IConnection CreateConnection(UriDescriptor endPointDescriptor)
        {
            if (_connection != null)
                return _connection;

            var path = endPointDescriptor.ComponentPath;
            var factory = new ConnectionFactory(string.Format("tcp://{0}/", path));
            var connection = factory.CreateConnection();
            return _connection = connection;
        }
Ejemplo n.º 19
0
        public void Connect()
        {
            while (!ableToSendEvents) {
                Uri connecturi = null;
                //if (textBoxSIPIPAddress.Text.StartsWith("ssl://"))
                //{
                Console.WriteLine ("Trying to connect to ActiveMQ broker ");
                //	connecturi = new Uri("activemq:" + textBoxSIPIPAddress.Text + ":" + textBoxSIPPort.Text + "?transport.ClientCertSubject=E%[email protected], CN%3DCommunication Tool"); // Connect to the ActiveMQ broker
                //}
                //else
                //{
                //log4.Debug(name + ": Trying to connect to ActiveMQ broker via non-secure connection");
                connecturi = new Uri ("activemq:tcp://localhost:61616"); // Connect to the ActiveMQ broker
                //}
                //Console.WriteLine("activeMQ::About to connect to " + connecturi);

                try {

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

                    // Create a new connection and session for publishing events
                    activeMQConnection = factory.CreateConnection ();
                    activeMQSession = activeMQConnection.CreateSession ();

                    IDestination destination = SessionUtil.GetDestination (activeMQSession, "topic://SIFTEO");
                    //Console.WriteLine("activeMQ::Using destination: " + destination);

                    // Create the producer
                    activeMQProducer = activeMQSession.CreateProducer (destination);
                    activeMQProducer.DeliveryMode = MsgDeliveryMode.Persistent;
                    destination = SessionUtil.GetDestination (activeMQSession, "topic://XVR.CCC");
                    activeMQConsumer = activeMQSession.CreateConsumer (destination);
                    //activeMQConsumer.Listener += new MessageListener(OnCCCMessage);

                    // Start the connection so that messages will be processed
                    activeMQConnection.Start ();
                    //activeMQProducer.Persistent = true;

                    // Enable the sending of events
                    //log4.Debug(name + ": ActiveMQ connected on topics XVR.CCC and XVR.SDK");
                    ableToSendEvents = true;

                } catch (Exception exp) {
                    // Report the problem in the output.log (Program Files (x86)\E-Semble\XVR 2012\XVR 2012\XVR_Data\output_log.txt)
                    //Console.WriteLine("*** AN ACTIVE MQ ERROR OCCURED: " + exp.ToString() + " ***");
                    //log4.Error(name + ": Error connecting to ActiveMQ broker: " + exp.Message);
                    //log4.Error((exp.InnerException != null) ? exp.InnerException.StackTrace : "");

                    Console.WriteLine (exp.Message);
                }
                System.Threading.Thread.Sleep (1000);
            }
        }
Ejemplo n.º 20
0
 public ActiveMQListener(string destQueue, MessageListener msgProcessor)
 {
     string brokerUrl = ConfigurationManager.AppSettings["BrokerURL"];
     ConnectionFactory connFactory = new ConnectionFactory(brokerUrl);
     IConnection conn = connFactory.CreateConnection();
     ISession session = conn.CreateSession();
     IDestination destination = SessionUtil.GetDestination(session, destQueue,DestinationType.Queue);
     IMessageConsumer consumer = session.CreateConsumer(destination);
     consumer.Listener += msgProcessor;
     conn.Start();
 }
Ejemplo n.º 21
0
        static async Task Main(string[] args)
        {
            await Task.Run(async() =>
            {
                while (true)
                {
                    Console.WriteLine("Waiting for 10s...");
                    await Task.Delay(TimeSpan.FromSeconds(10));

                    try
                    {
                        Uri connecturi = new Uri(UriString);
                        Console.WriteLine("About to connect to " + connecturi);

                        IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);

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

                                // Create a consumer
                                using (IMessageConsumer consumer = session.CreateConsumer(destination))
                                {
                                    // Start the connection so that messages will be processed.
                                    connection.Start();

                                    while (true)
                                    {
                                        Console.WriteLine("Waiting for message to consume.");

                                        // Consume a message
                                        ITextMessage message = consumer.Receive() as ITextMessage;
                                        if (message == null)
                                        {
                                            Console.WriteLine("No message received!");
                                        }
                                        else
                                        {
                                            Console.WriteLine("Received message with ID:   " + message.NMSMessageId);
                                            Console.WriteLine("Received message with text: " + message.Text);
                                        }
                                    }
                                }
                            }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            });
        }
Ejemplo n.º 22
0
        public static void Listen()
        {
            IDatabaseConnector dbConnector = new PgSqlDatabaseConnector();
            Uri connecturi = new Uri("activemq:tcp://es.giorgos.io:61616");

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

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

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    //ActiveMQQueue topic = new ActiveMQQueue("Consumer.ERIC.VirtualTopic.ESDATA");
                    ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic/ESDATA");

                    Console.WriteLine("Using destination: " + topic);

                    using (IMessageConsumer consumer = session.CreateConsumer(topic))
                    {
                        connection.Start();

                        consumer.Listener += new MessageListener(OnMessage);

                        while (true)
                        {
                            semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true);

                            if (message == null)
                            {
                                Console.WriteLine("No message received!");
                            }
                            else
                            {
                                IBytesMessage bmsg = message as IBytesMessage;
                                Console.WriteLine("Received message with ID:   " + bmsg.NMSMessageId);
                                var jsonString = System.Text.Encoding.UTF8.GetString(bmsg.Content);
                                AggregatedSamplingData data = JsonConvert.DeserializeObject <AggregatedSamplingData>(jsonString);
                                foreach (var sample in data.Samples)
                                {
                                    System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                                    dtDateTime = dtDateTime.AddSeconds(sample.Timestamp).ToUniversalTime();
                                    dbConnector.InsertDeviceData(sample.MeanAngleZ, sample.StdAcc, dtDateTime);
                                }
                                //Console.WriteLine("Received message with text: " + System.Text.Encoding.UTF8.GetString(bmsg.Content));
                            }
                        }
                    }
                }
        }
Ejemplo n.º 23
0
 public static void Send(string msg)
 {
     IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
        using (IConnection connection=factory.CreateConnection())
        {
        using (ISession session=connection.CreateSession())
        {
            IMessageProducer producer = session.CreateProducer(new ActiveMQQueue("test"));
            ITextMessage message = producer.CreateTextMessage(msg);
           // message.Properties.SetString("filter", "demo");
            producer.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);
        }
        }
 }
Ejemplo n.º 24
0
        public void RickyLogin(string name)
        {
            Uri connecturi = new Uri("failover:tcp://mq.checkmywwstats.com:61616");

            Trace.TraceInformation("About to connect to " + connecturi);
            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);

            _connection = factory.CreateConnection();
            _session    = _connection.CreateSession();
            // Examples for getting a destination:
            //
            // Hard coded destinations:
            //    IDestination destination = session.GetQueue("FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //    IDestination destination = session.GetTopic("FOO.BAR");
            //    Debug.Assert(destination is ITopic);
            //
            // Embedded destination type in the name:
            //    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //    IDestination destination = SessionUtil.GetDestination(session, "topic://FOO.BAR");
            //    Debug.Assert(destination is ITopic);
            //
            // Defaults to queue if type is not specified:
            //    IDestination destination = SessionUtil.GetDestination(session, "FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //
            // .NET 3.5 Supports Extension methods for a simplified syntax:
            //    IDestination destination = session.GetDestination("queue://FOO.BAR");
            //    Debug.Assert(destination is IQueue);
            //    IDestination destination = session.GetDestination("topic://FOO.BAR");
            //    Debug.Assert(destination is ITopic);
            //_readQueue = _session.CreateTemporaryQueue();
            DoLogin(name);

            IDestination destination = SessionUtil.GetDestination(_session, "queue://rickyraccoon.rand");

            _randRequestsQueue = _session.CreateConsumer(destination);

            destination    = SessionUtil.GetDestination(_session, "queue://rickyraccoon.playerin");
            _playerInQueue = _session.CreateConsumer(destination);

            // Start the connection so that messages will be processed.
            _connection.Start();


            _randRequestsQueue.Listener += new MessageListener(OnRandMessage);
            _playerInQueue.Listener     += new MessageListener(OnPlayerInMessage);
        }
Ejemplo n.º 25
0
        public ActiveMq(bool durable)
        {
            _connectionFactory = new ConnectionFactory("tcp://localhost:61616");
            _connectionFactory.AsyncSend = true;
            _connectionFactory.ProducerWindowSize = int.MaxValue;
            _connection = _connectionFactory.CreateConnection();
            _connection.ClientId = "13AC0CF8-65FE-4638-8B85-62210DD89BEE";
            _connection.Start();
            _session = _connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic("topic");
            _consumer = _session.CreateDurableConsumer(topic, "durable", "2 > 1", false);

            _producer = _session.CreateProducer(topic);
            _producer.DeliveryMode = durable ? MsgDeliveryMode.Persistent : MsgDeliveryMode.NonPersistent;
        }
Ejemplo n.º 26
0
 public void Send(string msg, string destQueue)
 {
     ConnectionFactory connFactory = new ConnectionFactory(brokerUrl);
     using (IConnection conn = connFactory.CreateConnection())
     {
         using (ISession session = conn.CreateSession())
         {
             IDestination destination = SessionUtil.GetDestination(session, destQueue);
             IMessageProducer producer = session.CreateProducer(destination);
             ITextMessage textMsg = session.CreateTextMessage(msg);
             //producer.Send(textMsg);
             producer.Send(textMsg, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.Zero);
         }
     }
 }
Ejemplo n.º 27
0
        private static IConnection CreateConnection(string clientId)
        {
            Console.WriteLine("Creating connection {0}", clientId);
            ConnectionFactory cf = new ConnectionFactory(_brokerUri, clientId)
            {
                AsyncSend = true,
                WatchTopicAdvisories = false,
                DispatchAsync = true
            };

            var connection = cf.CreateConnection();
            connection.Start();

            Console.WriteLine("Created connection {0}", clientId);
            return connection;
        }
 public override void ActivateOptions()
 {
    
     base.ActivateOptions();
     //setup the activemq connection 
     LogLog.Debug("Entering ActiveOptions in ActiveMQAppender");
     _connectionfactory = new ConnectionFactory(_connectionurl, "LOG4NET-Appenders-ActiveMQ-" + System.Guid.NewGuid().ToString());
     _connection = _connectionfactory.CreateConnection();
     _session = _connection.CreateSession();
     _producer = _session.CreateProducer();
     //TODO: This should be happening async since it could be blocking
     LogLog.Debug("Starting Connection");
     _connection.Start();
     LogLog.Debug("ActiveMQ Configured");
     
 }
Ejemplo n.º 29
0
        public static string Receive()
        {
            IConnectionFactory factory = new ConnectionFactory("tcp://192.168.1.103:61616");
               using (IConnection connection=factory.CreateConnection())
               {
               connection.ClientId = "test listener";
               connection.Start();
               using (ISession session=connection.CreateSession())
               {
                   IMessageConsumer consumer = session.CreateConsumer(new ActiveMQQueue("test"));
                   consumer.Listener += consumer_Listener;

               }
               }
               return Msg;
        }
Ejemplo n.º 30
0
        public void TestConnectionFactoryParseParams(
			[Values("tcp://${activemqhost}:61616", "activemq:tcp://${activemqhost}:61616")]
			string baseConnectionURI,
			[Values(AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.AutoAcknowledge)]
			AcknowledgementMode ackMode,
			[Values(true, false)]
			bool asyncSend,
			[Values(true, false)]
			bool alwaysSyncSend,
			[Values(true, false)]
			bool asyncClose,
			[Values(true, false)]
			bool copyMessageOnSend,
			[Values(3000, 1000)]
			int requestTimeout,
			[Values(true, false)]
			bool sendAcksAsync,
			[Values(true, false)]
			bool dispatchAsync)
        {
            string connectionURI = string.Format("{0}?" +
                                   "connection.AckMode={1}&" +
                                   "connection.AsyncSend={2}&" +
                                   "connection.AlwaysSyncSend={3}&" +
                                   "connection.AsyncClose={4}&" +
                                   "connection.CopyMessageOnSend={5}&" +
                                   "connection.RequestTimeout={6}&" +
                                   "connection.SendAcksAsync={7}&" +
                                   "connection.DispatchAsync={8}",
                                   baseConnectionURI, ackMode, asyncSend, alwaysSyncSend, asyncClose, copyMessageOnSend, requestTimeout, sendAcksAsync, dispatchAsync);

            ConnectionFactory factory = new ConnectionFactory(NMSTestSupport.ReplaceEnvVar(connectionURI));

            using(Connection connection = factory.CreateConnection() as Connection)
            {
                Assert.AreEqual(ackMode, connection.AcknowledgementMode);
                Assert.AreEqual(asyncSend, connection.AsyncSend);
                Assert.AreEqual(alwaysSyncSend, connection.AlwaysSyncSend);
                Assert.AreEqual(asyncClose, connection.AsyncClose);
                Assert.AreEqual(copyMessageOnSend, connection.CopyMessageOnSend);
                Assert.AreEqual(requestTimeout, connection.RequestTimeout.TotalMilliseconds);
                Assert.AreEqual(sendAcksAsync, connection.SendAcksAsync);
                Assert.AreEqual(dispatchAsync, connection.DispatchAsync);
            }
        }
Ejemplo n.º 31
0
        public IConnection CreateConnection(UriDescriptor endPointDescriptor)
        {
            if (_connection != null)
                return _connection;

            try
            {
                var path = endPointDescriptor.ComponentPath;
                var factory = new ConnectionFactory(string.Format("activemq:tcp://{0}/", path));
                var connection = factory.CreateConnection();
                connection.Start();
                return _connection = connection;
            }
            catch (Exception)
            {
                return null;
            }
        }
Ejemplo n.º 32
0
        private static IMapMessage GetBrokerStatistics()
        {
            lock (LockObj)
            {
                ConnectionFactory cf = new ConnectionFactory(SimulationParams.FromConfig().Broker1Address, "Stats")
                    {
                        RequestTimeout = 2000,
                        WatchTopicAdvisories = false,
                        AsyncSend = true,
                    };

                using (var connection = (Connection)cf.CreateConnection())
                {
                    connection.Start();
                    using (var session = connection.CreateSession())
                    using (var producer = session.CreateProducer())
                    {
                        IQueue replyTo = session.CreateTemporaryQueue();
                        using (var consumer = session.CreateConsumer(replyTo))
                        {
                            IQueue brokerStatsQueue = new ActiveMQQueue("ActiveMQ.Statistics.Broker");

                            IMessage msg = session.CreateMessage();
                            msg.NMSReplyTo = replyTo;

                            producer.Send(brokerStatsQueue, msg);

                            IMapMessage brokerStatistics = consumer.Receive(TimeSpan.FromSeconds(1)) as IMapMessage ?? new ActiveMQMapMessage();

                            consumer.Dispose();

                            connection.DeleteTemporaryDestination(replyTo); // due to https://issues.apache.org/jira/browse/AMQNET-378

                            return brokerStatistics;
                        }
                    }
                }
            }
        }
Ejemplo n.º 33
0
        public ITextMessage RequestText(String jobName, String verb, String body)
        {
            ITextMessage ecjResponse;
            ConnectionFactory connectionFactory = new ConnectionFactory(URI);
            try
            {
                using (IConnection connection = connectionFactory.CreateConnection())
                {
                    using (ISession session = connection.CreateSession())
                    {
                        ITemporaryQueue queue = session.CreateTemporaryQueue();
                        using (IMessageConsumer consumer = session.CreateConsumer(queue))
                        {
                            IMapMessage message = session.CreateMapMessage();
                            message.Body.SetString("VERB", verb);
                            message.Body.SetString("BODY", body);
                            message.Body.SetString("JOBNAME", jobName);
                            message.NMSReplyTo = queue;
                            string correlationId = Guid.NewGuid().ToString();
                            message.NMSCorrelationID = correlationId;
                            using (IMessageProducer producer = session.CreateProducer())
                            {
                                NmsDestinationAccessor destinationResolver = new NmsDestinationAccessor();
                                IDestination destination = destinationResolver.ResolveDestinationName(session, DESTINATION);
                                producer.Send(destination, message);
                            }
                            IMessage response = consumer.Receive(TimeSpan.FromSeconds(TIMEOUT_SECS));
                            ecjResponse = response as ITextMessage;

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Failed to send request", ex);
            }
            return ecjResponse;
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Verbindung zu einem ActiveMQ-Server aufbauen.
        /// </summary>
        /// <param name="url">Url-Angabe zu dem Server.</param>
        public void Connect(string url) 
        {
            try
            {
                var connecturi = new Uri(url);

                Debug.Print("MessageClient About to connect to " + connecturi);
                IConnectionFactory factory = new ConnectionFactory(connecturi);

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

                connection.Start();
                Debug.Print("MessageClient Connected Successful");
                workflowConsumers.Clear(); // alle consumer löschen!
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                throw;
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Configurate the Connection
        /// </summary>
        /// <param name="destination">Destionation</param>
        protected void Configure()
        {
            if (DoesConnectionExists())
            {
                return;
            }

            try
            {
                JmsDestination dest          = new JmsDestination(stringDestination);
                Uri            connectionUri = new Uri(dest.Host);
                Factory = new Apache.NMS.ActiveMQ.ConnectionFactory(dest.Host);
                IConnection connection = Factory.CreateConnection();
                connection.Start();
                if (connections.ContainsKey(ConnectorId))
                {
                    connections[ConnectorId].Add(stringDestination, connection);
                }
                else
                {
                    IDictionary <String, IConnection> tmp = new Dictionary <String, IConnection>();
                    tmp.Add(stringDestination, connection);
                    connections.Add(ConnectorId, tmp);
                }
            }
            catch (Exception ex)
            {
                // This allows it to invoke the method "Listen" again
                // The exception handler (if configured) invokes Changed
                // that will be forwarded to delegate (Object[] notUsed)
                Handling.Changed += delegate(Object[] notUsed)
                {
                    Configure();
                    return(null);
                };
                Handling.HandleException(ex);
            }
        }
Ejemplo n.º 36
0
        public Messenger()
        {
            initLogger();

            //zeromq opening connections
            zeromqQueue   = new BlockingQueue <String>();
            brokerQueue   = new BlockingQueue <String>();
            fileQueue     = new BlockingQueue <String>();
            loggerQueue   = new BlockingQueue <String>();
            zeromqContext = new Context(1);
            //reading parameters from the configuration file
            MESSAGING_TYPE        = Convert.ToInt32(ConfigurationManager.AppSettings.Get("MessagingType"));
            MAX_QUEUE_SIZE        = Convert.ToInt32(ConfigurationManager.AppSettings.Get("MAX_QUEUE_SIZE"));
            IGNORE_QUEUE_OVERFLOW = Convert.ToInt32(ConfigurationManager.AppSettings.Get("IGNORE_QUEUE_OVERFLOW"));
            BROKER = Convert.ToInt32(ConfigurationManager.AppSettings.Get("Broker"));
            String addressSend = ConfigurationManager.AppSettings.Get("WP4MessageAddress");

            fileStorageAddress = ConfigurationManager.AppSettings.Get("FileStorageAddress");
            maxFileStorageNum  = Convert.ToInt32(ConfigurationManager.AppSettings.Get("MAX_FILE_STORAGE_SIZE"));
            WAIT_COMMAND       = ConfigurationManager.AppSettings.Get("WAIT_COMMAND");
            FINISH_COMMAND     = ConfigurationManager.AppSettings.Get("FINISH_COMMAND");
            CONTINUE_COMMAND   = ConfigurationManager.AppSettings.Get("CONTINUE_COMMAND");
            MESSAGE_REQUEST    = ConfigurationManager.AppSettings.Get("MESSAGE_REQUEST");

            DB_LOGGING = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("DB_LOGGING"));
            //logging receiving socket
            if (DB_LOGGING == true)
            {
                String loggingDestinationPort = ConfigurationManager.AppSettings.Get("DBLoggingReceiver");
                loggerEmitter = zeromqContext.Socket(SocketType.PUSH);
                loggerEmitter.Bind(loggingDestinationPort);
                loggerThread = new Thread(new ThreadStart(this.LoggerThreadRun));
                loggerThread.Start();
            }

            switch (MESSAGING_TYPE)
            {
            case PIPELINE:
                //  Socket to send messages on
                zeromqSender = zeromqContext.Socket(SocketType.PUSH);
                //HWM doesnt work to limit zeromq queue size
                //sender.SetSockOpt(SocketOpt.HWM, 10);
                zeromqSender.Bind(addressSend);
                // to receive continue and wait messages from WP4
                String wp4SubscriberAddress = ConfigurationManager.AppSettings.Get("WP4SubscriberAddress");
                zeromqWP4Subscriber = zeromqContext.Socket(SocketType.SUB);
                zeromqWP4Subscriber.Bind(wp4SubscriberAddress);
                zeromqWP4Subscriber.Subscribe(ConfigurationManager.AppSettings.Get("WP4_COMMAND_FILTER"), Encoding.UTF8);
                break;

            case REQ_REP:
                //  Socket to send messages on
                zeromqSender = zeromqContext.Socket(SocketType.REP);
                zeromqSender.Bind(addressSend);
                break;
            }

            //starts zeromq messaging thread
            zerommqThread = new Thread(new ThreadStart(this.ZeromqThreadRun));
            zerommqThread.Start();

            if (IGNORE_QUEUE_OVERFLOW == OFF)
            {
                //Enables file storage for handling data peaks
                fileThread = new Thread(new ThreadStart(this.FileThreadRun));
                //Reads previously written messages if they are not sent to WP4
                readOldMessageFiles();
                fileThread.Start();
            }
            if (BROKER == ACTIVEMQ)
            {
                try
                {
                    //activemq opening connections
                    Apache.NMS.ActiveMQ.ConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(ConfigurationManager.AppSettings.Get("ACTIVEMQ"));
                    activeMQconnection = factory.CreateConnection();
                    Session      session = activeMQconnection.CreateSession(AcknowledgementMode.AutoAcknowledge) as Session;
                    IDestination bqueue  = session.GetQueue(ConfigurationManager.AppSettings.Get("QueueName"));
                    activemqSender = session.CreateProducer(bqueue);

                    brokerThread = new Thread(new ThreadStart(this.ActiveMQBrokerThreadRun));
                    brokerThread.Start();
                }
                catch (System.Exception e)
                {
                    //     IGNORE_QUEUE_OVERFLOW = 1;
                    BROKER = NONE;
                    logger.Error(e);
                }
            }
        }
Ejemplo n.º 37
-2
 static void Main(string[] args)
 {
     //创建连接工厂
     IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
     //通过工厂构建连接
     using (IConnection connection = factory.CreateConnection()) 
     {
         //这个是连接的客户端名称标识
         connection.ClientId = "firstQueueListener";
         //启动连接,监听的话要主动启动连接
         connection.Start();
         //通过连接创建一个会话
         using (ISession session = connection.CreateSession()) 
         {
             //通过会话创建一个消费者,这里就是Queue这种会话类型的监听参数设置
             IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("firstQueue"), "filter='demo'");
             //注册监听事件
             consumer.Listener += consumer_Listener;
         }
     }
     
     Console.ReadKey();
 }