public static void Main(string[] args) { 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", "61613")); String destination = arg(args, 0, "event"); String brokerUri = "stomp:tcp://" + host + ":" + port + "?transport.useLogging=true"; NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri); 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) { IMessage msg = consumer.Receive(); if (msg is ITextMessage) { ITextMessage txtMsg = msg as ITextMessage; String body = txtMsg.Text; if ("SHUTDOWN".Equals(body)) { TimeSpan diff = DateTime.Now - start; Console.WriteLine(String.Format("Received {0} in {1} seconds", count, (1.0*diff.TotalMilliseconds/1000.0))); break; } else { if (count == 0) { start = DateTime.Now; } count ++; if (count % 1000 == 0) { Console.WriteLine(String.Format("Received {0} messages.", count)); } } } else { Console.WriteLine("Unexpected message type: " + msg.GetType().Name); } } Console.WriteLine("Shutting down Listener."); connection.Close(); }
public ActionResult Create(string userUrl, bool addFriends, bool addMembersOfGroup) { if (addFriends && addMembersOfGroup) { return RedirectToAction("Create"); } //send message UserInformationToAdd information = new UserInformationToAdd(); information.url = userUrl; information.addFriends = addFriends; information.addMembersOfGroup = addMembersOfGroup; IConnectionFactory factory = new NMSConnectionFactory("tcp://localhost:61616"); IConnection connection = factory.CreateConnection(); connection = factory.CreateConnection(); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination QueueDestination = SessionUtil.GetDestination(session, "Users"); IMessageProducer MessageProducer = session.CreateProducer(QueueDestination); //IObjectMessage objMessage = session.CreateObjectMessage(information); //XStream xstream = new XStream(); //String xml = xstream.ToXml(information); string jsonString = JsonConvert.SerializeObject(information); ITextMessage textMessage = session.CreateTextMessage(jsonString); MessageProducer.Send(textMessage); session.Close(); connection.Stop(); return RedirectToAction("Index"); }
static void Main(string[] args) { var connecturi = new Uri("stomp:tcp://localhost:61613"); Console.WriteLine("About to connect to " + connecturi); var factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection("admin", "password")) using (var session = connection.CreateSession()) { connection.Start(); IDestination destination = session.GetTopic("perf"); using (IMessageProducer producer = session.CreateProducer(destination)) { producer.DeliveryMode = MsgDeliveryMode.NonPersistent; int sendMessages = 0; var watch = new Stopwatch(); watch.Start(); while (true) { ITextMessage message = session.CreateTextMessage(Message); producer.Send(message); sendMessages += 1; if (watch.ElapsedMilliseconds > 1000) { Console.WriteLine("{0} messages per second sent.", sendMessages); watch.Restart(); sendMessages = 0; } } } } }
public void ThenTheKlingonsReceiveTheFollowingGreetingMessage(string multilineText) { // Check that the Klingons receive the correct message on the outbound message queue AutoResetEvent semaphore = new AutoResetEvent(false); ITextMessage message = null; IConnectionFactory factory = new NMSConnectionFactory(new Uri("activemq:tcp://127.0.0.1:61616")); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, "queue://hello-adi-fuseesb.klingon.outbound"); using (IMessageConsumer consumer = session.CreateConsumer(destination)) { connection.Start(); consumer.Listener += new MessageListener((IMessage receivedMessage) => { message = receivedMessage as ITextMessage; semaphore.Set(); }); semaphore.WaitOne(10000, true); // Times out after 10 seconds Assert.IsNotNull(message); Utilities.Compare(multilineText, message.Text); } } }
/// <summary> /// 消息消费构造器 /// </summary> /// <param name="brokerUri">地址</param> /// <param name="username">用户名</param> /// <param name="psw">密码</param> /// <param name="clientId">客户端标识 兼做队列接收目的地</param> /// <param name="isClient">true 客户端;false 服务端</param> public OpenWireConsumer(string brokerUri, string username, string psw, string clientId,bool isClient) { NMSConnectionFactory _factory = new NMSConnectionFactory(brokerUri, clientId); _connection = _factory.CreateConnection(username, psw); _connection.Start(); _session = _connection.CreateSession(AcknowledgementMode.AutoAcknowledge); if (isClient) { _qReceiveDest = _session.GetDestination(clientId, DestinationType.TemporaryQueue); } else { _qReceiveDest = _session.GetQueue(clientId); } _messageConsumer = _session.CreateConsumer(_qReceiveDest); _messageConsumer.Listener += (message) => { if (Listener != null) { Listener(message); } }; }
internal IConnectionFactory CreateConnectionFactory() { if (providerFactory == null) { providerFactory = new NMSConnectionFactory(BrokerURI, properties); } return(providerFactory.ConnectionFactory); }
public void reciever() { IConnectionFactory factory = new NMSConnectionFactory("tcp://localhost:61616"); IConnection connection = factory.CreateConnection(); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination destination = SessionUtil.GetDestination(session, "Entity"); IMessageConsumer receiver = session.CreateConsumer(destination); receiver.Listener += new MessageListener(Message_Listener); connection.Stop(); }
public static void Main(string[] args) { NMSConnectionFactory NMSFactory = new NMSConnectionFactory("tcp://localhost:61616"); IConnection connection = NMSFactory.CreateConnection(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination destination = session.GetTopic("STOCKS.JAVA"); IMessageConsumer consumer = session.CreateConsumer(destination); consumer.Listener += new MessageListener(OnMessage); connection.Start(); Console.WriteLine("Press any key to quit."); Console.ReadKey(); }
public static InternalSession CreateInternalSession(XmlSetting entry) { string nm = entry.ReadSetting("@Name", ""); string brokerUri = entry.ReadSetting("@value"); object[] factoryParams = GetFactoryParams(entry.SelectOne("FactoryParams")); string clientId = entry.ReadSetting("ClientId/@value", null); // GetNodeValueAttribute(uriNode, "clientId", "NMSTestClientId"); string userName = entry.ReadSetting("UserName/@value"); //GetNodeValueAttribute(uriNode, "userName", "guest"); string passWord = entry.ReadSetting("PassWord/@value"); //GetNodeValueAttribute(uriNode, "passWord", "guest"); //string queueName = entry.ReadSetting("QueueName/@value"); //GetNodeValueAttribute(uriNode, "QueueName", "QueueName"); int timeout = 0; if (!int.TryParse(entry.ReadSetting("Timeout/@value", null), out timeout)) { timeout = 5; } try { Apache.NMS.NMSConnectionFactory nmsFactory = (null == factoryParams) ? new Apache.NMS.NMSConnectionFactory(brokerUri) : new Apache.NMS.NMSConnectionFactory(brokerUri, factoryParams); IConnection newConnection = nmsFactory.ConnectionFactory.CreateConnection(userName, passWord); if (newConnection == null) { throw new ApplicationException(string.Format("创建到 {0} 的连接失败!", brokerUri)); } newConnection.RequestTimeout = TimeSpan.FromSeconds(timeout); if (!string.IsNullOrEmpty(clientId)) { newConnection.ClientId = clientId; } return(new InternalSession(nm, newConnection , entry.ReadSetting("modelDestinationName/@value") , entry.ReadSetting("alertDestinationName/@value") , entry.ReadSetting("perfDestinationName/@value") , entry.ReadSetting("deskDestinationName/@value"))); } catch (Exception e) { return(new InternalSession(nm, new ApplicationException(string.Format("创建到 {0} 的连接失败!", brokerUri), e))); } }
protected void ProcessReceiveMessage() { while (this.isRuning) { try { IConnectionFactory factory = new NMSConnectionFactory(Static_ActiveMQ_Uri); using (IConnection connection = factory.CreateConnection()) { connection.ClientId = Guid.NewGuid().ToString(); connection.Start(); using (ISession session = connection.CreateSession()) using (IMessageConsumer consumer = session.CreateConsumer(new ActiveMQQueue(Static_ActiveMQ_Queue))) { Console.WriteLine(string.Format("建立与ActiveMQ的接收连接!", "ActiveMQ URI", Static_ActiveMQ_Uri, "ActiveMQ Queue", Static_ActiveMQ_Queue)); while (this.isRuning) { //IMessage.consumer.Listener += new MessageListener(this.OnMessageReceived); int receiveCount = 0; DateTime receiveStartTime = DateTime.Now; IMessage receivedMsg; // 使用同步的方式获取队列数据,以方便进行计算系统的处理性能 while ((receivedMsg = consumer.Receive(TimeSpan.FromMilliseconds(20))) != null) { this.OnMessageReceived(receivedMsg); receiveCount++; } if (receiveCount > 0) { TimeSpan span = DateTime.Now - receiveStartTime; Console.WriteLine(string.Format("Thread ID - {0}:从ActiveMQ接收到{1}条GPS数据,共开销{2}秒,平均{3}条/秒。", Thread.CurrentThread.ManagedThreadId, receiveCount, (double)span.TotalMilliseconds / 1000d, (double)receiveCount / (double)span.TotalMilliseconds * 1000d)); } Thread.Sleep(2000); } } } } catch (Exception ex) { Console.WriteLine("系统将在三十秒后重启与ActiveMQ的接收连接!", "ActiveMQ URI", Static_ActiveMQ_Uri, "ActiveMQ Queue", Static_ActiveMQ_Queue, "Exception", ex.Message); Thread.Sleep(30000); } } }
public Server() { InitializeComponent(); listBox1.DataSource = listener; //服务端 String brokerUri = "stomp:tcp://" + host + ":" + port + "?transport.useLogging=true"; factory = new NMSConnectionFactory(brokerUri); connection = factory.CreateConnection(user, password); connection.Start(); session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); consumer = session.CreateConsumer(session.GetQueue(re_destination)); producer = session.CreateProducer(); listener.Add("Starting up Listener."); listener.Add("Waiting for messages..."); t1 = new Thread(new ThreadStart(StartListener)); }
private void ClearInstances(bool dispose = false) { if (dispose && this.producers != null) { foreach (IMessageProducer p in producers) { p?.Dispose(); } } producers?.Clear(); if (dispose && this.consumers != null) { foreach (IMessageConsumer c in consumers) { c?.Dispose(); } } consumers?.Clear(); if (dispose && this.sessions != null) { foreach (ISession s in sessions) { s?.Close(); } } sessions?.Clear(); if (dispose && this.connections != null) { foreach (IConnection c in connections) { c?.Close(); } } connections?.Clear(); connectionFactories?.Clear(); providerFactory = null; }
private void SendActiveMQMessage(object arg) { List<GPSDataEntity> sendingData = arg as List<GPSDataEntity>; if (sendingData == null || sendingData.Count <= 0) return; try { // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. DateTime dt1 = DateTime.Now; IConnectionFactory factory = new NMSConnectionFactory(Static_ActiveMQ_Uri); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { // Create a producer using (IMessageProducer producer = session.CreateProducer(new ActiveMQQueue(Static_ActiveMQ_Queue))) { // Start the connection so that messages will be processed. //connection.Start(); for (int i = 0; i < sendingData.Count; i += Static_Sending_PageSize) { var transData = sendingData.GetRange(i, (sendingData.Count - i) < Static_Sending_PageSize ? sendingData.Count - i : Static_Sending_PageSize); // Send a message byte[] bytes = this.ConvertGPSData2Bytes(transData); IBytesMessage request = producer.CreateBytesMessage(bytes); producer.Send(request, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue); } } } TimeSpan span = DateTime.Now - dt1; Console.WriteLine(string.Format("共向ActiveMQ发送{0}*{1}条GPS数据,共开销{2}毫秒,平均{3}条/秒。", sendingData.Count, Static_Sending_PageSize, (double)span.TotalMilliseconds, (double)sendingData.Count / (double)span.TotalMilliseconds * 1000d)); } catch (Exception ex) { Console.WriteLine("Process报警数据转发失败"); Console.WriteLine(ex); } }
public static void Main(string[] args) { String user = env("STOMP_USER", "admin"); String password = env("STOMP_PASSWORD", "password"); String host = env("STOMP_HOST", "localhost"); int port = Int32.Parse(env("STOMP_PORT", "61613")); String destination = arg(args, 0, "event"); int messages = 10000; int size = 256; String DATA = "abcdefghijklmnopqrstuvwxyz"; String body = ""; for(int i=0; i < size; i ++) { body += DATA[i%DATA.Length]; } String brokerUri = "stomp:tcp://" + host + ":" + port; NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri); IConnection connection = factory.CreateConnection(user, password); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination dest = session.GetTopic(destination); IMessageProducer producer = session.CreateProducer(dest); producer.DeliveryMode = MsgDeliveryMode.NonPersistent; for (int i=1; i <= messages; i ++) { producer.Send(session.CreateTextMessage(body)); if ((i % 1000) == 0) { Console.WriteLine(String.Format("Sent {0} messages", i)); } } producer.Send(session.CreateTextMessage("SHUTDOWN")); connection.Close(); }
protected void Page_Load(object sender, EventArgs e) { Uri connectUri = new Uri("activemq:tcp://localhost:61616"); IConnectionFactory factory = new NMSConnectionFactory(connectUri); IConnection connection = factory.CreateConnection(); using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR"); IMessageConsumer consumer = session.CreateConsumer(destination); using (IMessageProducer producer = session.CreateProducer(destination)) { connection.Start(); //producer.per producer.RequestTimeout = receiveTimeout; consumer.Listener += new MessageListener(OnMessage); ITextMessage request = session.CreateTextMessage("Hello World"); request.NMSCorrelationID = "abc"; request.Properties["NMSXGroupID"] = "cheese"; request.Properties["myHeader"] = "Cheddar"; producer.Send(request); semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true); if (message == null) { } else { string messageId = message.NMSMessageId; string messageText = message.Text; } } } }
public Client() { InitializeComponent(); listBox2.DataSource = publisher; //客户端 String brokerUri2 = "stomp:tcp://" + host + ":" + port; factory2 = new NMSConnectionFactory(brokerUri2); connection2 = factory2.CreateConnection(user, password); connection2.Start(); session2 = connection2.CreateSession(AcknowledgementMode.AutoAcknowledge); dest2 = session2.GetQueue(se_destination); producer = session2.CreateProducer(dest2); consumer = session2.CreateConsumer(session2.GetQueue(re_destination)); consumer.Listener += (lllll) => { publisher.Add(String.Format("Receive {0} CorrelationId {1}", listenercount++, lllll.NMSCorrelationID)); }; publisher.Add("Starting up Publisher."); publisher.Add("Sending messages..."); t2 = new Thread(new ThreadStart(StartPublisher)); }
protected void ProcessReceiveMessage() { while (this.isRuning) { try { IConnectionFactory factory = new NMSConnectionFactory(this.activeMQUri); using (IConnection connection = factory.CreateConnection()) { connection.ClientId = Guid.NewGuid().ToString(); connection.Start(); using (ISession session = connection.CreateSession()) using (IMessageConsumer consumer = session.CreateConsumer(new ActiveMQQueue(this.activeMQQueue))) { Logger.Info(string.Format("建立与ActiveMQ的接收连接!", "ActiveMQ URI", this.activeMQUri, "ActiveMQ Queue", this.activeMQQueue)); while (this.isRuning) { //IMessage.consumer.Listener += new MessageListener(this.OnMessageReceived); // 使用同步的方式获取队列数据,以方便控制接收速度,及计算系统处理性能 IMessage receivedMsg; while ((receivedMsg = consumer.Receive(TimeSpan.FromMilliseconds(200))) != null) { this.OnMessageReceived(receivedMsg); } } } } } catch (Exception ex) { Logger.Fatal(ex); Logger.Fatal("系统将在三十秒后重启与ActiveMQ的接收连接!", "ActiveMQ URI", this.activeMQUri, "ActiveMQ Queue", this.activeMQQueue); Thread.Sleep(30000); } } Logger.Info("已退出线程"); }
public void TestConnection() { IConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(connectionUri)); using (connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, "queue://test.test.in"); using (IMessageConsumer consumer = session.CreateConsumer(destination)) { Connection amqConnection = connection as Connection; connection.ExceptionListener += ConnectionException; consumer.Listener += OnMessage; TcpFaultyTransport transport = amqConnection.ITransport.Narrow(typeof(TcpFaultyTransport)) as TcpFaultyTransport; Assert.IsNotNull(transport); transport.OnewayCommandPreProcessor += FailOnKeepAlive; Thread.Sleep(TimeSpan.FromSeconds(2)); connection.Start(); int count = 30; while (count-- > 0) { if (!connectionClosed) { Thread.Sleep(TimeSpan.FromSeconds(3)); } } Assert.IsTrue(connectionClosed); } } }
/// <summary> /// AMQP Hello World /// Using the AMQP protocol, send a message to a topic and retrieve that message again. /// </summary> /// <param name="uri">AMQP peer network address string. This string selects /// the Apache.NMS.AMQP provider and further specifies the TCP address and port of the /// peer AMQP entity.</param> /// <param name="protocolVersion">Selects AMQP protocol version. Use 'amqp0-10' or 'amqp1.0'. /// amqp1.0 is the default version if none is specified.</param> /// <param name="topicAddress">The name of the topic through which the message is passed /// in the AMQP peer.</param> /// </summary> public static void AMQP_HelloWorld(string uri, string protocolVersion, string topicAddress) { // AMQP Hello World // // Notes: // * Run qpidd broker, activemq broker, or dispatch router on given uri. // * Ensure the nmsprovider-amqp.config file exists // in the executable folder (build\net4-0\debug). // * Ensure the unmanaged qpid*.dll and boost*.dll files from // .nant\library\local\org.apache.qpid\Apache.Qpid\<version>\net-4.0\debug // are in project's Output Path (build\net-4.0\debug) so that they may be // loaded by org.apache.qpid.messaging.dll. try { Uri connecturi = new Uri(uri); Console.WriteLine("About to connect to " + connecturi); Hashtable props = new Hashtable(); props.Add("protocol", "amqp0-10"); props.Add("reconnect_timeout", 60); IConnectionFactory factory; if (false) factory = new NMSConnectionFactory(connecturi, "Bob", props); else factory = new NMSConnectionFactory(connecturi, "Bob", "protocol:amqp0-10", "reconnect_timeout:60"); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, topicAddress); // Create a consumer and producer using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { // Start the connection so that messages will be processed. connection.Start(); // Create a text message ITextMessage request = session.CreateTextMessage("Hello World!"); request.Properties["NMSXGroupID"] = "cheese"; request.Properties["myHeader"] = "Cheddar"; IMapMessage mmsg = session.CreateMapMessage(); mmsg.Body.SetString("key1", "value1"); mmsg.Properties["x-amqp-to"] = topicAddress; //Int64[] values = {10,200,3000,40000}; bool[] values = {true, false, true, false, true, false}; IObjectMessage objMsg = session.CreateObjectMessage(values); objMsg.Properties["number"] = 42; // For dispatch router 0.1 messages require a routing property request.Properties["x-amqp-to"] = topicAddress; // Send the message //producer.Send(request); //producer.Send(mmsg); producer.Send(objMsg); // Consume a message IMessage message = consumer.Receive(); if (message == null) { Console.WriteLine("No message received!"); } else { if (message is ITextMessage) { TextMessage tm = (TextMessage)message; Console.WriteLine("Received text message text: " + tm.Text); Console.WriteLine("Received text message properties: " + tm.Properties.ToString()); } else if (message is IMapMessage) { MapMessage mm = (MapMessage)message; Console.WriteLine("Received map message content: " + mm.Body.ToString()); Console.WriteLine("Received map message properties: " + mm.Properties.ToString()); } else if (message is IObjectMessage) { ObjectMessage om = (ObjectMessage)message; Object obj = om.Body; Console.WriteLine("Received object message content: " + obj.ToString()); Console.WriteLine("Received object message properties: " + om.Properties.ToString()); if (obj.GetType().IsArray) { Array valueArray = (Array)obj; for (int i =0; i<valueArray.Length; i++) { Console.WriteLine("Obj[{0}] = {1}", i, valueArray.GetValue(i)); } } } else { } } connection.Stop(); } } } catch (Exception e) { Console.WriteLine("Exception {0}.", e); } }
private void sendToStomp(string uri, string topic, string text, string link, string showparam, string username, string password) { try { Uri connecturi = new Uri(uri); // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection(username, password)) using (ISession session = connection.CreateSession()) { var destination = SessionUtil.GetDestination(session, topic.Replace("/topic/", ""), DestinationType.Topic); var topicListener = topic; var destinationListener = SessionUtil.GetDestination(session, topicListener.Replace("/topic/", ""), DestinationType.Topic); // Create a consumer and producer using (IMessageConsumer consumer = session.CreateConsumer(destinationListener)) using (IMessageProducer producer = session.CreateProducer(destination)) { // Start the connection so that messages will be processed. connection.Start(); producer.RequestTimeout = _receiveTimeout; consumer.Listener += OnMessage; // Send a message ITextMessage request = session.CreateTextMessage(showparam); if (!string.IsNullOrEmpty(link)) request.Properties["link"] = link; request.Properties["trigger-time"] = "NOW"; request.NMSPriority = MsgPriority.Highest; request.NMSDeliveryMode = MsgDeliveryMode.NonPersistent; request.NMSTimeToLive = TimeSpan.FromSeconds(15); request.NMSDestination = destination; request.Text = showparam; producer.DeliveryMode = MsgDeliveryMode.NonPersistent; producer.Send(request); // Wait for the message Semaphore.WaitOne((int) _receiveTimeout.TotalMilliseconds, true); if (_message == null) { // TODO Log no message received } else { // TODO Log message received } producer.Close(); consumer.Close(); } session.Close(); connection.Close(); } } catch (TypeLoadException) { // TODO could mean password is wrong and dll did not load } catch (Exception) { // TODO Log Exceptions } }
public static void Main(string[] args) { // This ID is important since it will be also the queue a response will be sent. string queueId = Guid.NewGuid().ToString(); // This message which should be send to the server string requestMessage = "" + "{" // the call ID; this will also be the queue a response will be sent. Be careful to make it unqiue + " \"callId\": \"" + queueId + "\"," // if the server should answer or not + " \"answer\": true," // of which type the sent data is; this have to be the required java types + " \"classes\": [" + " \"java.lang.String\"," + " \"org.openengsb.core.common.workflow.model.ProcessBag\"" + " ]," // the method which should be executed + " \"methodName\": \"executeWorkflow\"," // the "header-data" of the message; this is not the header of JMS to use eg stomp too + " \"metaData\": {" // the ID of the internal service to be called + " \"serviceId\": \"workflowService\"," // the context in which the service should be called + " \"contextId\": \"foo\"" + " }," // the arguments with which the workflowService method should be called + " \"args\": [" // the name of the workflow to be executed + " \"simpleFlow\"," // the params which should be put into the prcoess bag initially + " {" + " }" + " ]" + "}"; // the OpenEngSB connection URL Uri connecturi = new Uri("activemq:tcp://localhost:6549"); Console.WriteLine("About to connect to " + connecturi); // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination destination = session.GetDestination("receive"); Console.WriteLine("Using destination for sending: " + destination); using (IMessageProducer producer = session.CreateProducer(destination)) { connection.Start(); producer.DeliveryMode = MsgDeliveryMode.Persistent; ITextMessage request = session.CreateTextMessage(requestMessage); producer.Send(request); } IDestination receiveDest = session.GetDestination(queueId); Console.WriteLine("Using destination for receiving: " + receiveDest); using (IMessageConsumer consumer = session.CreateConsumer(receiveDest)) { ITextMessage message = consumer.Receive() as ITextMessage; if(message == null) { Console.WriteLine("No message received!"); } else { Console.WriteLine("Received message with text: " + message.Text); } } } Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
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://localhost: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); 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 = session.GetDestination("queue://FOO.BAR"); Console.WriteLine("Using destination: " + destination); // Create a consumer and producer using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { // Start the connection so that messages will be processed. connection.Start(); producer.DeliveryMode = MsgDeliveryMode.Persistent; // Send a message ITextMessage request = session.CreateTextMessage("Hello World!"); request.NMSCorrelationID = "abc"; request.Properties["NMSXGroupID"] = "cheese"; request.Properties["myHeader"] = "Cheddar"; producer.Send(request); // 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); } } } Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
private void sendToStomp(string address, int port, string topic, String link, String showparam) { try { Uri connecturi = new Uri("stomp:tcp://" + address + ":" + port+ ""); Log.log("new stomp transaction with " + connecturi.ToString() + "\ttopic:" + topic + "\tmessage:" + showparam + "", "STOMP"); // UIMain.errorAdd("[STOMP] About to connect to " + connecturi); // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection(CMSConfig.stomplogin, CMSConfig.stomppasscode)) using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, topic.Replace("/topic/", ""), DestinationType.Topic); String topicListener = topic.ToString(); if(topic.Contains("*")){ Log.log("*"); if (topic.Contains("/topic/fm/")) { Log.log("fm"); topicListener = topic.Replace("*", "10320"); } else if (topic.Contains("/topic/dab/")) { Log.log("dab"); topicListener = topic.Replace("*", "0"); } } IDestination destinationListener = SessionUtil.GetDestination(session, topicListener.Replace("/topic/", ""), DestinationType.Topic); UIMain.errorAdd("[STOMP] Using destination: " + destinationListener); //Console.WriteLine("[STOMP] " + destination + " " + showparam); // Create a consumer and producer using (IMessageConsumer consumer = session.CreateConsumer(destinationListener)) using (IMessageProducer producer = session.CreateProducer(destination)) { // Start the connection so that messages will be processed. connection.Start(); producer.RequestTimeout = receiveTimeout; consumer.Listener += new MessageListener(OnMessage); // Send a message ITextMessage request = session.CreateTextMessage(showparam); /* request.NMSCorrelationID = topic+""+DateTime.Now.ToFileTime().ToString(); request.Properties["NMSXGroupID"] = "EBURADIO" + DateTime.Now.ToFileTime().ToString(); request.Properties["myHeader"] = "Cheddar";*/ if(link!="") request.Properties["link"] = link; request.Properties["trigger-time"] = "NOW"; request.NMSPriority = MsgPriority.Highest; request.NMSDeliveryMode = MsgDeliveryMode.NonPersistent; request.NMSTimeToLive = TimeSpan.FromSeconds(15); request.NMSDestination = destination; request.Text = showparam; Log.log("Send : " + showparam); producer.DeliveryMode = MsgDeliveryMode.NonPersistent; producer.Send(request); // Wait for the message semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true); if (message == null) { Log.log(topic + "\tno message received from server", "STOMP"); UIMain.errorAdd("[STOMP] No message received!"); } else { Log.log("callback:"+ topic + "\tmessage received from server: "+message.Text+"\n********", "STOMP"); UIMain.errorAdd("callback:" + topic + "\tmessage received from server: " + message.Text + "\n********", "STOMP"); /* if (ContentManagerCore.debug) { UIMain.errorAdd(" [STOMP] Received message with ID: " + message.NMSMessageId); UIMain.errorAdd(" [STOMP] Received message with text: " + message.Text); }*/ } producer.Close(); consumer.Close(); } session.Close(); connection.Close(); } Log.log(topic + "\tSTOMP OK", "STOMP"); } catch (Exception e) { //UIMain.errorAdd("[STOMP] catch"); Log.log("catch exception : "+e.Message+" "+e.StackTrace, "STOMP"); } }
private void sendToStomp(string address, int port, string topic, String link, String showparam) { try { Uri connecturi = new Uri("stomp:tcp://" + address + ":" + port); // UIMain.errorAdd("[STOMP] About to connect to " + connecturi); // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection(System.Configuration.ConfigurationSettings.AppSettings["stompLogin"], System.Configuration.ConfigurationSettings.AppSettings["stompPasscode"])) using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, topic.Replace("/topic/", ""), DestinationType.Topic); // UIMain.errorAdd("[STOMP] Using destination: " + destination); Console.WriteLine("[STOMP] " + destination + " " + showparam); // Create a consumer and producer using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { // Start the connection so that messages will be processed. connection.Start(); producer.RequestTimeout = receiveTimeout; consumer.Listener += new MessageListener(OnMessage); // Send a message ITextMessage request = session.CreateTextMessage(showparam); //request.NMSCorrelationID = topic; //request.Properties["NMSXGroupID"] = "EBURADIO"; //request.Properties["myHeader"] = "Cheddar"; if(link!="") request.Properties["link"] = link; request.Properties["trigger-time"] = "now"; producer.Send(request); // Wait for the message semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true); if (message == null) { UIMain.errorAdd("[STOMP] No message received!"); } else { UIMain.errorAdd("[STOMP] Received message with ID: " + message.NMSMessageId); UIMain.errorAdd("[STOMP] Received message with text: " + message.Text); } producer.Close(); consumer.Close(); } session.Close(); connection.Close(); } } catch (Exception e) { //UIMain.errorAdd("[STOMP] catch"); Console.WriteLine("[STOMP] catch : " + e.Message); } }
public MQTemplate(string activeMqSpec) { _activeMqSpec = activeMqSpec; var oldSkooluri = new Uri(_activeMqSpec).LocalPath.Replace("(", string.Empty).Replace(")", string.Empty); _factory = new NMSConnectionFactory(oldSkooluri); }
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://localhost:6549"); Console.WriteLine("About to connect to " + connecturi); // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { // 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); // This queue have to be specified on the server during the creation of the proxy IDestination destination = session.GetDestination("queue://FOO.BAR"); Console.WriteLine("Using incomming destination: " + destination); // Create a consumer and producer using (IMessageConsumer consumer = session.CreateConsumer(destination)) { // Start the connection so that messages will be processed. connection.Start(); // Consume a message ITextMessage message = consumer.Receive(new TimeSpan(1,0,0)) 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); JavaScriptSerializer ser = new JavaScriptSerializer(); Request requestMapping = (Request) ser.Deserialize(message.Text, typeof(Request)); if(requestMapping.methodName == "getAliveState") { IDestination outgoingDestination = session.GetDestination("queue://"+requestMapping.callId); Console.WriteLine("Using outgoing destination: " + outgoingDestination); using (IMessageProducer producer = session.CreateProducer(outgoingDestination)) { Response responseMapping = ProduceAnswerMapping(ser, requestMapping); String answer = ser.Serialize(responseMapping); Console.WriteLine("Created answer text: " + answer); // Send a message producer.DeliveryMode = MsgDeliveryMode.Persistent; ITextMessage request = session.CreateTextMessage(answer); producer.Send(request); } } else { Console.WriteLine("Unknown method; ignore..."); } } } Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } }
private void StartConnection() { Uri connecturi = new Uri(string.Format("activemq:tcp://{0}:{1}", JMSHostname, JMSPort)); //Console.WriteLine("About to connect to " + connecturi); // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder. IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection()) { connection.ClientId = "DD4TJMSListener-" + Guid.NewGuid().ToString(); connection.ExceptionListener += connection_ExceptionListener; connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge)) { //IDestination destination = session.GetDestination(Topic); IDestination destination = session.GetTopic(JMSTopic); Logger.Debug("using destination: " + destination); Debug.WriteLine("using destination: " + destination); using (IMessageConsumer consumer = session.CreateConsumer(destination)) { IMessage message; try { while ((message = consumer.Receive(ReceiveTimeout)) != null) { OnInvalidate(message); } } catch (Exception e) { Logger.Error("Error receiving messages: {0}", e.ToString()); } } //// Create a consumer and producer //using (IMessageConsumer consumer = session.CreateDurableConsumer(topic, "DD4TJMSConsumer", "2 > 1", false)) //{ // // Start the connection so that messages will be processed. // connection.Start(); // consumer.Listener += new MessageListener(OnInvalidate); //} //// stay in this thread to keep the connection to the JMS server open //// This method should only be called from a background thread! //while (true) //{ //} } } }
/// <summary> /// Processes JMS messages /// </summary> private static void ProcessMessages() { IConnectionFactory factory = new NMSConnectionFactory(new Uri("activemq:tcp://127.0.0.1:61616")); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination source = SessionUtil.GetDestination(session, "queue://hello-adi-fuseesb.klingon.outbound"); IDestination destination = SessionUtil.GetDestination(session, "queue://hello-adi-fuseesb.klingon.inbound"); using (IMessageProducer producer = session.CreateProducer(destination)) using (IMessageConsumer consumer = session.CreateConsumer(source)) { connection.Start(); consumer.Listener += new MessageListener((IMessage receivedMessage) => { var message = receivedMessage as ITextMessage; // Convert message to XML and extract the message id and greeting XmlDocument doc = new XmlDocument(); doc.LoadXml(message.Text); var id = doc.SelectSingleNode("/Greeting/@id").Value; var greeting = doc.SelectSingleNode("/Greeting").InnerXml; // Send back a message string response = string.Format("<GreetingResponse id=\"{0}\">{1}</GreetingResponse>", id, greeting); producer.Send(session.CreateTextMessage(response)); }); while (true) { Thread.Sleep(100); } } } }
/// <summary> /// 消息发送 /// </summary> /// <param name="brokerUri">Apollo地址</param> /// <param name="username">用户名</param> /// <param name="psw">密码</param> /// <param name="qsenddest">队列发送目的地</param> /// <param name="isClient">true 客户端;false 服务端</param> public OpenWireProducer(string brokerUri,string username,string psw,string qsenddest,bool isClient) { NMSConnectionFactory _factory = new NMSConnectionFactory(brokerUri); _connection = _factory.CreateConnection(username, psw); _connection.Start(); _session = _connection.CreateSession(AcknowledgementMode.AutoAcknowledge); if (isClient) { _qSendDest = _session.GetQueue(qsenddest); _messageProducer = _session.CreateProducer(_qSendDest); } else { //服务端不需要发送地址 _messageProducer = _session.CreateProducer(); } _messageProducer.DeliveryMode = MsgDeliveryMode.NonPersistent;//非持久化 }
/// <summary> /// Processes JMS messages /// </summary> private static void PurgeQueues() { IConnectionFactory factory = new NMSConnectionFactory(new Uri("activemq:tcp://127.0.0.1:61616")); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination source = SessionUtil.GetDestination(session, "queue://hello-adi-fuseesb.klingon.outbound"); using (IMessageConsumer consumer = session.CreateConsumer(source)) { connection.Start(); ITextMessage message = null; do { message = consumer.Receive(new TimeSpan(10000)) as ITextMessage; } while (message != null); } } }
public void WhenTheKlingonsSendTheFollowingResponse(string multilineText) { // Put an appropriate response onto the ESB message queue IConnectionFactory factory = new NMSConnectionFactory(new Uri("activemq:tcp://127.0.0.1:61616")); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination destination = SessionUtil.GetDestination(session, "queue://hello-adi-fuseesb.klingon.inbound"); using (IMessageProducer producer = session.CreateProducer(destination)) { ITextMessage request = session.CreateTextMessage(multilineText); producer.Send(request); } } }