public static void ReceiveMsg() { Apache.NMS.IConnection con = null; try { var factory = new ConnectionFactory(brokerUrl); factory.UserName = "******"; factory.Password = "******"; factory.ClientId = "MsgApp-Receiver1"; factory.PrefetchPolicy = new PrefetchPolicy() { DurableTopicPrefetch = 1, TopicPrefetch = 1 }; var rpolicy = new RedeliveryPolicy(); rpolicy.InitialRedeliveryDelay = 15000; rpolicy.MaximumRedeliveries = 5; rpolicy.UseExponentialBackOff = false; using (con = factory.CreateConnection("admin", "admin")) { con.RedeliveryPolicy = rpolicy; //con.AcknowledgementMode = AcknowledgementMode.ClientAcknowledge; using (var session = con.CreateSession(AcknowledgementMode.ClientAcknowledge)) { var dest = session.GetTopic(topicName); var durableConsumer = session.CreateDurableConsumer(dest, "durable-eol-orderMsgSubscriber1", null, false); con.Start(); durableConsumer.Listener += (msg) => { Console.WriteLine("durable-eol-orderMsgSubscriber-1: " + ((ActiveMQTextMessage)msg).Text); if ((msg as ActiveMQTextMessage).Text.StartsWith("0")) { msg.Acknowledge(); } else { session.Recover(); } }; Console.ReadKey(); durableConsumer.Close(); } } } catch (Exception ex) { string emsg = ex.Message; } finally { con.Dispose(); } }
protected virtual void Dispose(bool disposing) { if (this.isDisposed) { return; } if (disposing) { if (this.queueSession != null) { if (this.queueSession.AcknowledgementMode == AcknowledgementMode.Transactional) { this.queueSession.Rollback(); } // there is a difference between calling dispose and Close on AMQ.Session object this.queueSession.Close(); } if (this.queueConnection != null) { this.queueConnection.Dispose(); } } this.queueSession = null; this.queueConnection = null; this.isDisposed = true; }
public CaptureDTO Popup(string userId) { var sysUser = _sysUserRepository.GetById(userId.ToInt()); if (sysUser.IsNotNull() && !sysUser.SysChannels.IsNullOrEmpty()) { var sb = new StringBuilder(); sysUser.SysChannels.ToList().ForEach(t => sb.Append($"or channel='{t.Name}' ")); var selector = sb.ToString().TrimStart('o', 'r').TrimEnd(' '); var rtnJson = string.Empty; IConnectionFactory factory = new ConnectionFactory(ConfigPara.MQIdaddress); //Create the connection using (Apache.NMS.IConnection connection = factory.CreateConnection()) { try { connection.ClientId = "SKCustome" + userId; connection.Start(); //Create the Session using (ISession session = connection.CreateSession()) { IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("MQMessage"), sysUser.Name, selector, false); var i = 10; while (i > 0) { ITextMessage msg = (ITextMessage)consumer.Receive(new TimeSpan(1000)); if (msg != null) { rtnJson = msg.Text; } i--; } consumer.Close(); } } catch { } finally { connection.Stop(); connection.Close(); } } var capture = rtnJson.ToObject <Capture>(); if (capture.IsNotNull()) { if (capture.CreateTime.AddMinutes(2) > DateTime.Now) { return(capture.ConvertoDto <Capture, CaptureDTO>()); } } } return(default(CaptureDTO)); }
public void Initialize(bool transactionMode) { Apache.NMS.IConnectionFactory connectionFactory = new Apache.NMS.ActiveMQ.ConnectionFactory(this.configurationProvider.GetConfigurationSection <QueueingConfig>().QueueServerUri); this.queueConnection = connectionFactory.CreateConnection(); this.queueConnection.ClientId = this.connectionNameProvider.GetConnectionName(); this.queueSession = this.queueConnection.CreateSession(transactionMode ? Apache.NMS.AcknowledgementMode.Transactional : Apache.NMS.AcknowledgementMode.AutoAcknowledge); }
public void PublishMsgToTopic(string brokerUrl, string topicName) { Apache.NMS.IConnection con = null; ITextMessage msg = null; try { var factory = new ConnectionFactory(brokerUrl); // factory.PrefetchPolicy = new PrefetchPolicy() { DurableTopicPrefetch = 1, TopicPrefetch = 1 }; con = factory.CreateConnection("admin", "admin"); con.ClientId = "OrderMsgProducer-1"; con.RequestTimeout = TimeSpan.FromMinutes(5); con.Start(); using (var session = con.CreateSession(Apache.NMS.AcknowledgementMode.ClientAcknowledge)) { var dest = (IDestination)session.GetTopic(topicName); var prod = session.CreateProducer(dest); prod.DeliveryMode = MsgDeliveryMode.NonPersistent; prod.TimeToLive = TimeSpan.FromMinutes(20); do { Console.WriteLine("Please enter msg"); var textMsg = Console.ReadLine(); msg = prod.CreateTextMessage(textMsg); msg.Properties.SetLong("x-opt-delivery-delay", 10000); prod.Send(msg); msg.ClearBody(); Console.WriteLine("Please press esc key to exit."); } while (Console.ReadKey().Key != ConsoleKey.Escape); prod.Close(); } } catch (Exception ex) { string emsg = ex.Message; } finally { con.Close(); con.Dispose(); } }
public static void Run() { logger.Info("注册监听MQ事件"); Task.Factory.StartNew(() => { try { //Create the Connection factory IConnectionFactory factory = new ConnectionFactory(ConfigPara.MQIdaddress); //Create the connection using (Apache.NMS.IConnection connection = factory.CreateConnection()) { connection.ClientId = "MQtesting listener"; connection.Start(); //Create the Session using (ISession session = connection.CreateSession()) { IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("MQMessage"), "webapi listener", null, false); while (true) { ITextMessage msg = (ITextMessage)consumer.Receive(new TimeSpan(10000)); if (msg != null) { logger.Info(msg.Text); if (Clients != null) { Clients.All.broadcastMessage(msg.Text); } } Thread.Sleep(2000); } } } } catch (System.Exception e) { logger.Info(e.Message); } }); logger.Info("监听完成"); }
public override void Listen() { string queueName = "TextQueue"; string brokerUri = $"activemq:tcp://localhost:61616"; // Default port NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri); using (Apache.NMS.IConnection connection = factory.CreateConnection()) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge)) using (IDestination dest = session.GetQueue(queueName)) using (IMessageConsumer consumer = session.CreateConsumer(dest)) { IMessage msg = consumer.Receive(); try { if ((msg is ITextMessage) == false) { throw new Exception("Unexpected message type: " + msg.GetType().Name); } ITextMessage txtMsg = msg as ITextMessage; string jsonMessage = txtMsg.Text; var messageContext = DesypherMessageType(jsonMessage); Interpret(messageContext); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { msg.Acknowledge(); } } } }
public static void ReceiveMsg2() { Apache.NMS.IConnection con = null; try { var factory = new ConnectionFactory(brokerUrl); factory.UserName = "******"; factory.Password = "******"; factory.ClientId = "MsgApp-Receiver2"; // factory.SendTimeout = 300000; //5 mins using (con = factory.CreateConnection()) { using (var session = con.CreateSession(Apache.NMS.AcknowledgementMode.ClientAcknowledge)) { var dest = session.GetTopic(topicName); var durableConsumer = session.CreateDurableConsumer(dest, "durable-eol-orderMsgSubscriber2", null, false); con.Start(); durableConsumer.Listener += (msg) => { Console.WriteLine("durable-eol-orderMsgSubscriber-2: " + ((ITextMessage)msg).Text); msg.Acknowledge(); }; Console.ReadKey(); durableConsumer.Close(); } } } catch (Exception ex) { string emsg = ex.Message; } finally { con.Dispose(); } }
private void OpenConnection(Apache.NMS.IConnection connection, Queue queue) { if (queue != null && !queue.RedeliveryPolicy.UseAMQScheduler) { connection.RedeliveryPolicy = new Apache.NMS.Policies.RedeliveryPolicy { BackOffMultiplier = queue.RedeliveryPolicy.BackOffMultiplier, InitialRedeliveryDelay = queue.RedeliveryPolicy.InitialRedeliveryDelay, MaximumRedeliveries = queue.RedeliveryPolicy.MaximumRedeliveries, UseExponentialBackOff = queue.RedeliveryPolicy.UseExponentialBackOff, CollisionAvoidancePercent = queue.RedeliveryPolicy.CollisionAvoidancePercent, UseCollisionAvoidance = queue.RedeliveryPolicy.UseCollisionAvoidance }; } else { connection.RedeliveryPolicy = new Apache.NMS.Policies.RedeliveryPolicy { MaximumRedeliveries = 0 }; } connection.Start(); }
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); } } }