Example #1
0
        private void btn_GoiKham_Click(object sender, EventArgs e)
        {
            try
            {
                int        i  = lst_ChoKham.SelectedIndex;
                ePhieuKham bn = new ePhieuKham();
                bn = (ePhieuKham)lst_ChoKham.Items[i];
                MessageBox.Show("Đã gọi thành công");
                lst_ChoKham.Items.RemoveAt(lst_ChoKham.SelectedIndex);
                IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
                IConnection        con     = factory.CreateConnection("admin", "admin");
                con.Start();

                ISession         session     = con.CreateSession(AcknowledgementMode.AutoAcknowledge);
                ActiveMQTopic    destination = new ActiveMQTopic("topicKiemTra");
                IMessageProducer producer    = session.CreateProducer(destination);
                IMessage         msg         = new ActiveMQTextMessage(txtMaPhieu.Text.Trim());
                producer.Send(msg);
                session.Close();
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi" + ex.Message);
            }
        }
Example #2
0
        private void TruyenData()
        {
            IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
            IConnection        con     = factory.CreateConnection("admin", "admin");

            con.Start();
            ISession         session     = con.CreateSession(AcknowledgementMode.AutoAcknowledge);
            ActiveMQTopic    destination = new ActiveMQTopic("PhongKhamNhaKhoa");
            IMessageProducer producer    = session.CreateProducer(destination);

            ePhieuKham p = new ePhieuKham();

            p.idPhieuKham = idPhieuKham;
            p.idNV        = 1;
            p.ngayDKKham  = DateTime.Today;
            p.tinhTrang   = 1;
            p.moTa        = txtmota.Text.Trim();
            p.idKH        = Convert.ToInt32(idKhachHang);

            string   xml = new ObjectToXml <ePhieuKham>().object2XML(p);
            IMessage msg = new ActiveMQTextMessage(xml);

            producer.Send(msg);
            session.Close();
            con.Close();
        }
Example #3
0
        public void TestCopy()
        {
            this.nmsMessageID     = "ID:1141:45278:429";
            this.nmsCorrelationID = "testcorrelationid";
            this.nmsDestination   = new ActiveMQTopic("test.topic");
            this.nmsReplyTo       = new ActiveMQTempTopic("test.replyto.topic:001");
            this.nmsDeliveryMode  = MsgDeliveryMode.NonPersistent;
            this.nmsType          = "test type";
            this.nmsPriority      = MsgPriority.High;
            this.nmsTimestamp     = DateTime.Now;

            ActiveMQMessage msg1 = new ActiveMQMessage();

            msg1.NMSMessageId       = this.nmsMessageID;
            msg1.NMSCorrelationID   = this.nmsCorrelationID;
            msg1.FromDestination    = this.nmsDestination;
            msg1.NMSReplyTo         = this.nmsReplyTo;
            msg1.NMSDeliveryMode    = this.nmsDeliveryMode;
            msg1.NMSType            = this.nmsType;
            msg1.NMSPriority        = this.nmsPriority;
            msg1.NMSTimestamp       = this.nmsTimestamp;
            msg1.ReadOnlyProperties = true;

            ActiveMQMessage msg2 = msg1.Clone() as ActiveMQMessage;

            Assert.IsTrue(msg1.NMSMessageId.Equals(msg2.NMSMessageId));
            Assert.IsTrue(msg1.NMSCorrelationID.Equals(msg2.NMSCorrelationID));
            Assert.IsTrue(msg1.NMSDestination.Equals(msg2.NMSDestination));
            Assert.IsTrue(msg1.NMSReplyTo.Equals(msg2.NMSReplyTo));
            Assert.IsTrue(msg1.NMSDeliveryMode == msg2.NMSDeliveryMode);
            Assert.IsTrue(msg1.NMSRedelivered == msg2.NMSRedelivered);
            Assert.IsTrue(msg1.NMSType.Equals(msg2.NMSType));
            Assert.IsTrue(msg1.NMSPriority == msg2.NMSPriority);
            Assert.IsTrue(msg1.NMSTimestamp == msg2.NMSTimestamp);
        }
Example #4
0
 public void Publish(IntegrationEvent integrationEvent)
 {
     try
     {
         if (integrationEvent.GetType() == typeof(MessageEvent))
         {
             MessageEvent  msgEvent = (MessageEvent)integrationEvent;
             ActiveMQTopic topic    = new ActiveMQTopic(msgEvent.getEventType());
             using (IMessageProducer producer = this.session.CreateProducer(topic))
             {
                 producer.DeliveryMode = MsgDeliveryMode.Persistent;
                 ITextMessage message = session.CreateTextMessage(msgEvent.getText());
                 foreach (String key in msgEvent.getProperties().Keys)
                 {
                     message.Properties[key] = msgEvent.getObjectProperty(key);
                 }
                 message.Properties["destination"] = msgEvent.getEventType();
                 try
                 {
                     producer.Send(message);
                 }
                 catch (NMSException ex)
                 {
                     throw new NMSException("Could not send a message ", ex);
                 }
             }
         }
     }
     catch (NMSException ex)
     {
         throw new NMSException("Could not publish this event", ex);
     }
 }
Example #5
0
 /// <summary>
 /// 订阅主题
 /// </summary>
 /// <param name="config"></param>
 /// <param name="ClientId"></param>
 /// <param name="ac"></param>
 public static void SubscriberTopic(AQConfig config, string clientId, Action <MessageResult> ac = null)
 {
     if (!subTopic.ContainsKey(clientId))
     {
         var factory = new ConnectionFactory(config._AQConfigConnectString);
         var conn    = factory.CreateConnection();
         conn.ClientId = clientId;
         conn.Start();
         var session = conn.CreateSession();
         var topic   = new ActiveMQTopic(config.ActiveMQName);
         IMessageConsumer consumer = session.CreateDurableConsumer(topic, clientId, null, false);
         if (ac != null)
         {
             consumer.Listener += new MessageListener((m) =>
             {
                 ac(new MessageResult()
                 {
                     custom   = clientId,
                     IMessage = m
                 });
             });
         }
         subTopic.Add(clientId, new SubTopic()
         {
             ConnectionFactory = factory,
             connection        = conn,
             session           = session
         });
     }
 }
        //
        // Write the booleans that this object uses to a BooleanStream
        //
        public override int TightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs)
        {
            ActiveMQTopic info = (ActiveMQTopic)o;

            int rc = base.TightMarshal1(wireFormat, info, bs);

            return(rc + 0);
        }
Example #7
0
        private void init()
        {
            IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");

            destination = new ActiveMQTopic("chat");
            IConnection con = factory.CreateConnection("admin", "admin");

            con.Start();
            session = con.CreateSession(AcknowledgementMode.AutoAcknowledge);
            IMessageConsumer consumer = session.CreateConsumer(destination);
        }
        public TopicPublisher(string topicName, string brokerUri)               //set all the variables
        {
            this.topicName         = topicName;
            this.connectionFactory = new ConnectionFactory(brokerUri);
            this.connection        = this.connectionFactory.CreateConnection();
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic(topicName);

            this.producer = this.session.CreateProducer(topic);
        }
        private void ReceiverThongTinTopic()
        {
            IConnectionFactory factory    = new ConnectionFactory("tcp://localhost:61616");
            IConnection        connection = factory.CreateConnection("admin", "admin");

            connection.Start();
            ISession         session       = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            ActiveMQTopic    topic         = new ActiveMQTopic("DuongChiHieu_17044781_Topic");
            IMessageConsumer consumertopic = session.CreateConsumer(topic);

            consumertopic.Listener += Consumertopic_Listener;
        }
Example #10
0
        public TopicPublisher(String topicName, string brokerUri)
        {
            this.topicName         = topicName;
            this.connectionFactory = new ConnectionFactory(brokerUri);
            this.connection        = connectionFactory.CreateConnection();
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic(topicName);

            this.producer = session.CreateProducer(topic);
            this.producer.DeliveryMode = MsgDeliveryMode.Persistent;
        }
        public void start()
        {
            var connectionFactory = new ConnectionFactory(broker, Environment.MachineName);

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

            session = connection.CreateSession();

            var topic = new ActiveMQTopic(destination);

            consumer = session.CreateDurableConsumer(topic, "surveillance_app", null, false);

            consumer.Listener += (message =>
            {
                var textMessage = (ITextMessage)message;

                var what = HttpUtility.HtmlDecode(textMessage.Properties.GetString("WHAT"));
                var where = HttpUtility.HtmlDecode(textMessage.Properties.GetString("WHERE"));
                var companies = textMessage.Properties.GetInt("companies.total");

                if (String.IsNullOrEmpty(what))
                {
                    return;
                }
                if (companies == 0)
                {
                    return;
                }

                if (nmsTextProviderPredicate.IsMatch(textMessage))
                {
                    var userAgentType = GetUserAgentType(textMessage);

                    if (nmsTextProviderPredicate.IsStandardSearch(textMessage, where))
                    {
                        if (OnText != null)
                        {
                            OnText(this, new TextEventArgs(what + " @ " + where, userAgentType, false));
                        }
                    }

                    if (nmsTextProviderPredicate.IsGeoSearch(textMessage))
                    {
                        if (OnText != null)
                        {
                            OnText(this, new TextEventArgs(what + " @", userAgentType, true));
                        }
                    }
                }
            });
        }
        public event MessageReceivedDelegate OnMessageReceived;                                        //callback delegate for whenever we receive a message

        public TopicSubscriber(string topicName, string brokerUri, string clientId, string consumerId) //set all of the variables
        {
            this.topicName           = topicName;
            this.connectionFactory   = new ConnectionFactory(brokerUri);
            this.connection          = this.connectionFactory.CreateConnection();
            this.connection.ClientId = clientId;
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic(topicName);

            this.consumer           = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false);
            this.consumer.Listener += new MessageListener(OnMessage);
        }
        public MonitoringMessagePublisher() // read from config file. TODO!!!
        {
            this.topicName         = GetQueueTopicString();
            this.connectionFactory = new ConnectionFactory(GetQueueBrokerURIString());


            this.connection = this.connectionFactory.CreateConnection();
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic(topicName);

            this.producer = this.session.CreateProducer(topic);
        }
Example #14
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));
                            }
                        }
                    }
                }
        }
Example #15
0
 private void DoInternalSubscription(String eventKey)
 {
     try
     {
         ActiveMQTopic    topic      = new ActiveMQTopic(eventKey);
         var              newSession = this.connection.CreateSession();
         IMessageConsumer consumer   = newSession.CreateConsumer(topic);
         consumer.Listener += new MessageListener(ReceiveMessage);
     }
     catch (NMSException ex)
     {
         throw new NMSException("Could not subscribe", ex);
     }
 }
Example #16
0
        public void WhenRequestDeferredMessages_AMessageIsSentToTheAMQSchedulerTopic()
        {
            IMessage sentMessage = null;
            var      destination = new ActiveMQTopic("someTopic");
            var      session     = this.SetupCreateSession();
            var      producer    = SetupCreateTopicProducer(session, ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION);

            producer.Setup(p => p.Send(It.IsAny <IMessage>())).Callback <IMessage>(m => sentMessage = m);

            this.testee.RequestDeferredMessages(destination);

            sentMessage.Should().NotBeNull();
            sentMessage.NMSReplyTo.Should().Be(destination);
            sentMessage.Properties.Keys.Should().Contain(ScheduledMessage.AMQ_SCHEDULER_ACTION);
            sentMessage.Properties[ScheduledMessage.AMQ_SCHEDULER_ACTION].Should().Be(ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE);
        }
Example #17
0
        public TopicSubscriber(string topicName, string brokerUri, string clientId)
        {
            this.topicName      = topicName;
            connectionFactory   = new ConnectionFactory(brokerUri);
            connection          = this.connectionFactory.CreateConnection();
            connection.ClientId = clientId;
            if (connection.IsStarted)
            {
                connection.Stop();
            }
            connection.Start();
            session = connection.CreateSession();
            var topic = new ActiveMQTopic(topicName);

            consumer           = this.session.CreateDurableConsumer(topic, clientId, null, false);
            consumer.Listener += new MessageListener(OnMessage);
        }
        /// <summary>
        /// Subscribe to a set of topics to the message queue
        /// </summary>
        /// <param name="topics">Topics</param>
        public void Subscribe(IEnumerable <string> topics)
        {
            if (topics == null)
            {
                throw new ArgumentNullException(nameof(topics));
            }
            // filter duplicate topics
            var topicSet = new HashSet <string>();

            foreach (var topic in topics)
            {
                topicSet.Add(topic);
            }
            var name        = string.Join(",", topicSet).Replace('#', '*');
            var destination = new ActiveMQTopic(name);

            _consumer = _session.CreateConsumer(destination);
        }
Example #19
0
        private void frmKhamBenh_Load(object sender, EventArgs e)
        {
            txtKB_tenBS.Text = nhaSiWCFClient.getNhabyID(idNV).tenNhaSi;
            IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
            IConnection        con     = factory.CreateConnection("admin", "admin");

            con.Start();
            ISession         session     = con.CreateSession(AcknowledgementMode.AutoAcknowledge);
            ActiveMQTopic    destination = new ActiveMQTopic("phieuKham");
            IMessageConsumer consumer    = session.CreateConsumer(destination);

            consumer.Listener += Consumer_Listener;

            ActiveMQTopic    kiemTra    = new ActiveMQTopic("topicKiemTra");
            IMessageConsumer consumerkt = session.CreateConsumer(kiemTra);

            consumerkt.Listener += Consumerkt_Listener;
        }
Example #20
0
        private void SendThongTinTopic(eBenhNhan bn)
        {
            IConnectionFactory factory    = new ConnectionFactory("tcp://localhost:61616");
            IConnection        connection = factory.CreateConnection("admin", "admin");

            connection.Start();
            ISession      session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            ActiveMQTopic topic   = new ActiveMQTopic("DuongChiHieu_17044781_Topic");

            IMessageProducer    producer = session.CreateProducer(topic);
            string              x        = new ConvertXML <eBenhNhan>().O2XML(bn);
            ActiveMQTextMessage mes      = new ActiveMQTextMessage(x);

            producer.Send(mes);
            producer.Close();
            session.Close();
            connection.Close();
        }
Example #21
0
        public virtual void SetUp()
        {
            this.nmsMessageID     = "testid";
            this.nmsCorrelationID = "testcorrelationid";
            this.nmsDestination   = new ActiveMQTopic("TEST.test.topic");
            this.nmsReplyTo       = new ActiveMQTempTopic("TEST.test.replyto.topic:001");
            this.nmsDeliveryMode  = MsgDeliveryMode.NonPersistent;
            this.nmsRedelivered   = true;
            this.nmsType          = "test type";
            this.nmsPriority      = MsgPriority.High;
            this.nmsTimestamp     = DateTime.Now;
            this.consumerIDs      = new long[3];

            for (int i = 0; i < this.consumerIDs.Length; i++)
            {
                this.consumerIDs[i] = i;
            }
        }
Example #22
0
        public void Post([FromBody] int nid)
        {
            Console.WriteLine("------------------ Received");
            Uri connecturi             = new Uri("activemq:tcp://es.giorgos.io:61616");
            IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic/ESNOTIF");
                    using (IMessageProducer producer = session.CreateProducer(topic))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;
                        ITextMessage request = session.CreateTextMessage("Notification Received");
                        producer.Send(request);
                    }
                }
        }
Example #23
0
 /// <summary>
 /// 发送主题文本消息
 /// </summary>
 /// <param name="config"></param>
 /// <param name="textMsg"></param>
 public static void SendTopicMessage(AQConfig config, string textMsg)
 {
     if (!string.IsNullOrEmpty(textMsg))
     {
         var factory = new ConnectionFactory(config._AQConfigConnectString);
         //创建连接
         using (var _connection = factory.CreateConnection())
         {
             using (ISession session = _connection.CreateSession())
             {
                 //创建一个主题
                 IDestination destination = new ActiveMQTopic(config.ActiveMQName);
                 //创建生产者
                 IMessageProducer producer = session.CreateProducer(destination);
                 //创建一个文本消息
                 var _message = producer.CreateTextMessage(textMsg);
                 //发送消息
                 producer.Send(_message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);
             }
         }
     }
 }
        public SimpleTopicSubscriber(string topicName, string brokerUri, string clientId, string consumerId)
        {
            this.topicName           = topicName + "?consumer.retroactive=true";
            this.connectionFactory   = new ConnectionFactory(brokerUri);
            this.connection          = this.connectionFactory.CreateConnection();
            this.connection.ClientId = clientId;
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic(topicName);

            this.consumer = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false);
//var mesnagem = consumer.Receive()
//var message = (ActiveMQTextMessage)consumer.Receive(TimeSpan.FromSeconds(3000));
//var message = (ActiveMQTextMessage)consumer.Receive(TimeSpan.FromMinutes(30));

//Console.WriteLine (message.Text);
//Console.WriteLine ("--------------------------");
//Console.WriteLine (message.Text);
//Console.WriteLine ("--------------------------");

//this.consumer = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false);
            this.consumer.Listener += new MessageListener(OnMessage);
        }
        public void TestMessagePullCache2()
        {
            TrackingTransport      transport = new TrackingTransport();
            ConnectionStateTracker tracker   = new ConnectionStateTracker();

            tracker.TrackMessages = true;

            tracker.MaxCacheSize = 10;
            ConnectionData conn = CreateConnectionState(tracker);

            for (int i = 0; i < 100; ++i)
            {
                MessagePull         pull        = new MessagePull();
                ActiveMQDestination destination = new ActiveMQTopic("TEST");
                pull.ConsumerId  = conn.consumer.ConsumerId;
                pull.Destination = destination;
                tracker.ProcessMessagePull(pull);
                tracker.TrackBack(pull);
            }

            tracker.DoRestore(transport);

            Assert.AreEqual(1, transport.messagePulls.Count);
        }
Example #26
0
        public 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://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())
                {
                    // 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);
                    //IDestination destination = SessionUtil.GetDestination(session, "queue://Consumer.esb.VirtualTopic.es-data");
                    //ActiveMQQueue topic = new ActiveMQQueue("Consumer.ERIC.VirtualTopic.ESDATA");
                    ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic/ESDATA");

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

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

                        consumer.Listener += new MessageListener(OnMessage);

                        /*
                         * // Send a message
                         * ITextMessage request = session.CreateTextMessage("Hello World!");
                         * request.NMSCorrelationID = "abc";
                         * request.Properties["NMSXGroupID"] = "cheese";
                         * request.Properties["myHeader"] = "Cheddar";
                         *
                         * producer.Send(request);
                         */

                        while (true)
                        {
                            // Wait for the message
                            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);
                                Console.WriteLine("Received message with text: " + System.Text.Encoding.UTF8.GetString(bmsg.Content));
                            }
                        }
                    }
                }
        }
Example #27
0
        public async void AmazonMQStreamer([FromQuery] int messageToSend = 10, [FromQuery] int delayBtwMessageInMs = 50)
        {
            NMSConnectionFactory factory = new NMSConnectionFactory(ActiveMqEndpoint);

            var rd = new Random(100);

            var histogram = new LongHistogram(TimeStamp.Hours(1), 3);

            var writer = new StringWriter();

            string[] currencyPairs = new string[] { "EUR/USD", "EUR/JPY", "EUR/GBP", "USD/JPY", "USD/GBP" };
            for (int currIndex = 0; currIndex < currencyPairs.Length; currIndex++)
            {
                var pair = currencyPairs[currIndex];
                Task.Run(async() =>
                {
                    using (var connection = factory.CreateConnection(ActiveMqLogin, ActiveMqMdp))
                    {
                        connection.Start();

                        var session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);

                        var topic = new ActiveMQTopic("VirtualTopic." + pair);

                        var producer = session.CreateProducer(topic);

                        producer.DeliveryMode = MsgDeliveryMode.NonPersistent;


                        for (var i = 0; i <= messageToSend; i++)
                        {
                            var currency = new Currency()
                            {
                                Id           = i,
                                CurrencyType = pair,
                                Price        = rd.NextDouble(),
                                Timestamp    = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString(),
                                Ladders      = new LadderFactory().Build(10)
                            };

                            var cur             = JsonConvert.SerializeObject(currency);
                            long startTimestamp = Stopwatch.GetTimestamp();

                            producer.Send(session.CreateTextMessage(cur));

                            long elapsed = Stopwatch.GetTimestamp() - startTimestamp;
                            histogram.RecordValue(elapsed);
                            await Task.Delay(delayBtwMessageInMs).ConfigureAwait(false);
                        }
                        session.Close();
                        connection.Close();

                        var scalingRatio = OutputScalingFactor.TimeStampToMilliseconds;
                        histogram.OutputPercentileDistribution(
                            writer,
                            outputValueUnitScalingRatio: scalingRatio);
                        System.IO.File.WriteAllText(@"d:\cloud\amq.txt", writer.ToString());
                    }
                });
            }
        }