public virtual object DeserializeMessage(ITextMessage amqMessage, Type type) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(amqMessage.Text))) { return this.messageSerializer.Deserialize(stream, new[] { type }).Single(); } }
private static IMessage GetResponseMessage(INetTxSession session, ITextMessage textMessage) { IMessage responseMessage; if (nextResponseType == 0) { var errorCode = new Random().Next(2) == 1 ? ResponseCode.Ok : ResponseCode.Failed; responseMessage = session.CreateTextMessage(""); responseMessage.Properties["ErrorCode"] = (int)errorCode; nextResponseType = 1; } else { var messageContent = new ResponseToPublisher { ResponseId = Guid.NewGuid(), Time = DateTime.Now.Second > -1 ? (DateTime?)DateTime.Now : null, Duration = TimeSpan.FromSeconds(99999D), }; responseMessage = session.CreateXmlMessage(messageContent); nextResponseType = 0; } responseMessage.NMSCorrelationID = textMessage.NMSMessageId; return responseMessage; }
private static string TryToGetReplyToQueueName(ITextMessage amqMessage) { if (amqMessage.NMSReplyTo == null) { return string.Empty; } return ((IQueue)amqMessage.NMSReplyTo).QueueName; }
public virtual void ProcessMessage(ITextMessage amqMessage) { Type type = this.messageTypeInterpreter.GetTypeFromNmsType(amqMessage.NMSType); object message = this.messageDeserializer.DeserializeMessage(amqMessage, type); CorrelationIdAndAddress correlationIdAndAddress = this.correlationIdAndAddressTranscoder.TranscodeCorrelationIdAndAddress( amqMessage.NMSCorrelationID ?? amqMessage.NMSMessageId, TryToGetReplyToQueueName(amqMessage)); this.messageSender.SendMessage( message, correlationIdAndAddress, type); }
public void SetUp() { A.Fake<IConnectionFactory>(); _connection = A.Fake<IConnection>(); _lazyConnection = new Lazy<IConnection>(() => { _connection.Start(); return _connection; }); _session = A.Fake<ISession>(); _producer = A.Fake<IMessageProducer>(); _serializer = A.Fake<IMessageSerializer>(); _destination = A.Fake<IDestination>(); _message = A.Fake<ITextMessage>(); _messagePropertyProvider = A.Fake<IMessagePropertyProvider<IMessage>>(); A.CallTo(() => _connection.CreateSession(A<Apache.NMS.AcknowledgementMode>.Ignored)).Returns(_session); A.CallTo(() => _session.CreateProducer(_destination)).Returns(_producer); A.CallTo(() => _session.CreateTextMessage(A<string>._)).Returns(_message); A.CallTo(() => _serializer.Serialize(A<object>._)).Returns("SerializedString"); _testScheduler = new TestScheduler(); _publisher = new MessagePublisher<IMessage>(_lazyConnection, _destination, _serializer, _messagePropertyProvider, _testScheduler); }
protected void AssertEquals(ITextMessage m1, ITextMessage m2) { AssertEquals(m1, m2, ""); }
[ProducerSetup("default", "testdest4", "pro4")]//*/ public void TestMultipleConsumerMessageListenerReceive() { const int NUM_MSGS = 100000; string[] conIds = new string[] { "con1", "con2", "con3", "con4" }; string[] proIds = new string[] { "pro1", "pro2", "pro3", "pro4" }; IList <IMessageConsumer> consumers = this.GetConsumers(conIds); IList <IMessageProducer> producers = this.GetProducers(proIds); int ProducerCount = producers.Count; int ConsumerCount = consumers.Count; long[] lastMsgId = new long[ConsumerCount]; long[] MissingMsgCount = new long[ConsumerCount]; long lostMsgCount = 0; int TotalMsgs = NUM_MSGS * ProducerCount; long undeliveredMsgCount = TotalMsgs; int timeout = Math.Max(TotalMsgs / 1000, 1) * 1100; MsgDeliveryMode mode = MsgDeliveryMode.NonPersistent; using (IConnection connection = this.GetConnection("default")) { connection.ExceptionListener += DefaultExceptionListener; for (int i = 0; i < ConsumerCount; i++) { lastMsgId[i] = -1; MissingMsgCount[i] = 0; } try { MessageListener callback = CreateListener(TotalMsgs); int index = 0; foreach (IMessageConsumer consumer in consumers) { int num = index; MessageListener countingCallback = (m) => { long lastId = lastMsgId[num]; long msgId = ExtractMsgId(m.NMSMessageId); if (msgId > lastId) { lastMsgId[num] = msgId; if (lastId != -1) { MissingMsgCount[num] += (msgId - (lastId + 1)); lostMsgCount += (msgId - (lastId + 1)); } } callback(m); // signal envent waiter when the last expected msg is delivered on all consumers if (lostMsgCount + msgCount == TotalMsgs) { // signal if detected lost msgs from id gap and delivered msgs make the total msgs. waiter?.Set(); } else if (lastMsgId[num] == NUM_MSGS - 1) { // signal if final msg id on every consumer is detected. undeliveredMsgCount -= NUM_MSGS; if (undeliveredMsgCount <= 0) { waiter?.Set(); } } }; consumer.Listener += countingCallback; index++; } connection.Start(); // send messages to Destinations ITextMessage sendMsg = producers[0].CreateTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { int link = 0; foreach (IMessageProducer producer in producers) { sendMsg.Text = "Link: " + link + ", num:" + i; link++; producer.Send(sendMsg, mode, MsgPriority.Normal, TimeSpan.Zero); } } if (!waiter.WaitOne(timeout)) { if (mode.Equals(MsgDeliveryMode.NonPersistent)) { if (msgCount != TotalMsgs) { Logger.Warn(string.Format("Only received {0} of {1} messages in {2}ms.", msgCount, TotalMsgs, timeout)); LogSummary(MissingMsgCount, lastMsgId, NUM_MSGS); } Assert.IsNull(asyncEx, "Received unexpected asynchronous exception. Message : {0}", asyncEx?.Message); } else { Assert.Fail("Only received {0} of {1} messages in {2}ms.", msgCount, TotalMsgs, timeout); } } else { if (msgCount != TotalMsgs) { Logger.Warn(string.Format("Only received {0} of {1} messages in {2}ms.", msgCount, TotalMsgs, timeout)); LogSummary(MissingMsgCount, lastMsgId, NUM_MSGS); } Assert.IsNull(asyncEx, "Received unexpected asynchronous exception. Message : {0}", asyncEx?.Message); long ActualMsgs = mode.Equals(MsgDeliveryMode.NonPersistent) ? msgCount + lostMsgCount : msgCount; Assert.AreEqual(TotalMsgs, ActualMsgs, "Only received {0} (delivered = {1}, lost = {2}) of {3} messages in {4}ms.", ActualMsgs, msgCount, lostMsgCount, TotalMsgs, timeout); } } catch (Exception ex) { this.PrintTestFailureAndAssert(GetTestMethodName(), "Unexpected Exception.", ex); } finally { // sleep for 2 seconds to allow for pending procuder acknowledgements to be received from the broker. System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); } } }
public void TestReceiveStopStartMessageAsync() { const int NUM_MSGS = 100; const int MESSAGE_RECEIVE_TIMEOUT = 1000; // 1.0s //Apache.NMS.Util.Atomic<bool> stopped = new Apache.NMS.Util.Atomic<bool>(false); using (IConnection connection = this.GetConnection()) using (IMessageConsumer consumer = this.GetConsumer("con1")) using (IMessageProducer producer = this.GetProducer("pro1")) { try { MessageListener ackcallback = CreateListener(NUM_MSGS); MessageListener callback = (m) => { if (!connection.IsStarted) { waiter.Set(); throw new Exception("Received Message " + msgCount + " on stopped connection."); } ackcallback(m); Logger.Info("MsgCount : " + msgCount); }; consumer.Listener += callback; connection.ExceptionListener += DefaultExceptionListener; connection.Start(); ITextMessage message = producer.CreateTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.Text = "num:" + i; producer.Send(message); if (i == NUM_MSGS / 2) { connection.Stop(); Logger.Info("Stopping Connection. At message " + i + "."); } else if (i == NUM_MSGS - 1) { Logger.Info("Starting Connection. At message " + i + "."); connection.Start(); } } if (!waiter.WaitOne(MESSAGE_RECEIVE_TIMEOUT)) { Assert.IsNull(asyncEx, "OnExceptionListener Event when raised. Message : {0}.", asyncEx?.Message); Assert.Fail("Received {0} of {1} messages in {2}ms.", msgCount, NUM_MSGS, MESSAGE_RECEIVE_TIMEOUT); } Assert.IsNull(asyncEx, "OnExceptionListener Event when raised. Message : {0}.", asyncEx?.Message); Assert.AreEqual(NUM_MSGS, msgCount, "Failed to Received All Messages sent."); } catch (Exception ex) { Logger.Warn("Async execption: " + this.GetTestException(asyncEx)); this.PrintTestFailureAndAssert(this.GetMethodName(), "Unexpected Exception.", ex); } } }
static void Main(string[] args) { int numProducers = args[0] != null?Int32.Parse(args[1]) : 1; int numConsumers = args[1] != null?Int32.Parse(args[1]) : 1; Uri failoveruri = new Uri("activemq:failover:tcp://localhost:61616,tcp://localhost:61617"); for (int i = 0; i < numProducers; i++) { var id = i; Thread producerThread = new Thread(() => RunProducer(id)); producerThread.Start(); Thread.Sleep(1000); } for (int i = 0; i < numConsumers; i++) { var id = i; Thread consumerThread = new Thread(() => RunConsumer(id)); consumerThread.Start(); Thread.Sleep(1000); } void RunProducer(int id) { Console.WriteLine("Producer " + id + " is connecting..."); IConnectionFactory factory = new NMSConnectionFactory(failoveruri); using (IConnection connection = factory.CreateConnection()) { connection.ClientId = "producer" + id; using (ISession session = connection.CreateSession()) { ITopic ordersTopic = SessionUtil.GetTopic(session, "topic://orders"); using (IMessageProducer olineOrderProducer = session.CreateProducer()) { connection.Start(); olineOrderProducer.DeliveryMode = MsgDeliveryMode.Persistent; while (true) { olineOrderProducer.Send(ordersTopic, session.CreateTextMessage("order placed!")); Thread.Sleep(1000); } } } } } void RunConsumer(int id) { Console.WriteLine("Consumer " + id + " is connecting..."); IConnectionFactory factory = new NMSConnectionFactory(failoveruri); using (IConnection connection = factory.CreateConnection()) { connection.ClientId = "consumer" + id; using (ISession session = connection.CreateSession()) { ITopic ordersTopic = SessionUtil.GetTopic(session, "topic://orders"); using (IMessageConsumer someConsumer = session.CreateDurableConsumer(ordersTopic, "orders-consumer", null, false)) { connection.Start(); while (true) { ITextMessage message = someConsumer.ReceiveNoWait() as ITextMessage; if (message != null) { Console.WriteLine("recieved: " + message.Text); } } } } } } }
public void ReloadData() { if (_AsyncReadThread != null) { if (_AsyncReadThread.IsAlive) { return; // Already fetching data } } _AsyncReadThread = new Thread(() => { if (isStopping) { return; } try { // Consume a message semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true); if (message == null) { //selfReference.UpdateText("No message received!" + "\n"); } else { if (lastMessage != null) { if (lastMessage.NMSMessageId == message.NMSMessageId) { return; //sameMessage } else { this.lastMessage = message; } } else { this.lastMessage = message; } message.Acknowledge(); if (debug) { selfReference.UpdateText("Received message with text: " + message.Text); } GameplayTypes gameTypes = GameplayTypes.NONE; if (message.Properties.Contains("GameType")) { gameTypes = (GameplayTypes)Enum.Parse(typeof(GameplayTypes), message.Properties.GetString("GameType")); } switch (gameTypes) { case GameplayTypes.Connect: HandleConnectionMessage(); break; case GameplayTypes.Disconnect: HandleDisconnectMessage(); break; case GameplayTypes.Initialised: HandleInitialisedMessage(); break; case GameplayTypes.Movement: break; case GameplayTypes.Turn: break; case GameplayTypes.Surrender: break; default: //No Default Handler break; } } } catch (Exception e) { //selfReference.UpdateText(e.Message + " -" + e.GetBaseException().ToString() + "\n"); } }); _AsyncReadThread.Start(); }
private void OnTextMessage(ITextMessage message) { var executors = _contextExecutors .OfType<SourcedContextExecutor<ITextMessage>>() .Where(e => e.ShouldExecute(message)); RunExecutors(executors, message); }
/// <summary> /// Gets the type of the target given the message. /// </summary> /// <param name="message">The message.</param> /// <returns>Type of the target</returns> protected virtual Type GetTargetType(ITextMessage message) { return typeMapper.ToType(message.Properties.GetString(typeMapper.TypeIdFieldName)); }
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.api.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); }
/// <summary> /// Gets the type of the target given the message. /// </summary> /// <param name="message">The message.</param> /// <returns>Type of the target</returns> protected virtual Type GetTargetType(ITextMessage message) { return(typeMapper.ToType(message.Properties.GetString(typeMapper.TypeIdFieldName))); }
private void RecvMessage(ITextMessage message) { DoAction(message.Text); textBox1.Text = message.Text; }
private void consumer_Listener(IMessage message) { ITextMessage msg = (ITextMessage)message; textBox1.Invoke(new DelegateRevMessage(RecvMessage), msg); }
private void consumer_Listener(IMessage message) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); ITextMessage msg = (ITextMessage)message; // 收到消息后,将当前应用激活,并置于最前面 HandleRunningInstance(); if (msg.Text.Trim() != "") { string text = msg.Text.Trim(); XmlDocument xmlDoc = new XmlDocument(); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { xmlDoc.LoadXml(text); XmlNode node = xmlDoc.SelectSingleNode("Content/Message"); if (node != null) { string pwoNo = ""; string t107Code = ""; int t47LeafID = 0; int t216LeafID = 0; int t133LeafID = 0; int t20LeafID = 0; List <XtraTabPage> removepages = new List <XtraTabPage>(); DateTime sendTime = DateTime.Now; if (node.Attributes["ExCode"] != null && node.Attributes["ExCode"].Value == "RefreshSPCShow") { if (node.Attributes["Optype"] != null && node.Attributes["Optype"].Value == "D") { if (node.Attributes["StationID"] != null && node.Attributes["StationID"].Value == macAddress) { if (node.Attributes["SysLogID"] != null && node.Attributes["SysLogID"].Value == stationUser.SysLogID.ToString()) { if (node.Attributes["T107Code"] != null) { t107Code = node.Attributes["T107Code"].Value; foreach (XtraTabPage page in tcMain.TabPages) { if (t107Code == (page.Tag as WIPStationProductionStatus).T107Code) { removepages.Add(page); } } foreach (XtraTabPage page in removepages) { RemoveTab(page); } consumers[t107Code].Close(); consumers.Remove(t107Code); } } } } } else { if (node.Attributes["T107Code"] != null) { t107Code = node.Attributes["T107Code"].Value; } else { return; } //if (node.Attributes["PWONo"] != null) // pwoNo = node.Attributes["PWONo"].Value; //else // return; //if (node.Attributes["T47LeafID"] != null) // t47LeafID = int.Parse(node.Attributes["T47LeafID"].Value); //else // return; //if (node.Attributes["T216LeafID"] != null) // t216LeafID = int.Parse(node.Attributes["T216LeafID"].Value); //else // return; //if (node.Attributes["T133LeafID"] != null) // t133LeafID = int.Parse(node.Attributes["T133LeafID"].Value); //else // return; //if (node.Attributes["T20LeafID"] != null) // t20LeafID = int.Parse(node.Attributes["T20LeafID"].Value); //else // return; if (node.Attributes["SendDateTime"] != null) { sendTime = DateTime.Parse(node.Attributes["SendDateTime"].Value); } else { sendTime = DateTime.Now; } if ((DateTime.Now - sendTime).TotalSeconds <= 180) { // 切换到消息中指定工位的显示面板 object[] parameters = new object[7]; parameters[0] = tcMain; parameters[1] = t107Code; parameters[2] = pwoNo; parameters[3] = t47LeafID; parameters[4] = t216LeafID; parameters[5] = t133LeafID; parameters[6] = t20LeafID; BeginInvoke(new RedrawingSPCChartMethod(RedrawingSPCChart), parameters); } } } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } }
public void TestCloseConsumerBeforeCommit() { ITextMessage[] outbound = new ITextMessage[] { session.CreateTextMessage("First IMessage"), session.CreateTextMessage("Second IMessage")}; // lets consume any outstanding messages from prev test runs BeginTx(); bool needCommit = false; while(consumer.ReceiveNoWait() != null) { needCommit = true; } if(needCommit) { CommitTx(); } // sends the messages BeginTx(); producer.Send(outbound[0]); producer.Send(outbound[1]); CommitTx(); BeginTx(); ITextMessage message = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.AreEqual(outbound[0].Text, message.Text); // Close the consumer before the Commit. This should not cause the // received message to Rollback. consumer.Close(); CommitTx(); // Create a new consumer consumer = CreateMessageConsumer(); BeginTx(); message = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(message); Assert.AreEqual(outbound[1].Text, message.Text); CommitTx(); }
private async Task DoSendingMessageNonPersistentTestImpl(bool anonymousProducer, bool setPriority, bool setOnProducer) { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { //Add capability to indicate support for ANONYMOUS-RELAY Symbol[] serverCapabilities = { SymbolUtil.OPEN_CAPABILITY_ANONYMOUS_RELAY }; IConnection connection = await EstablishConnectionAsync(testPeer, serverCapabilities : serverCapabilities); testPeer.ExpectBegin(); string queueName = "myQueue"; Action <object> targetMatcher = t => { var target = t as Target; Assert.IsNotNull(target); if (anonymousProducer) { Assert.IsNull(target.Address); } else { Assert.AreEqual(queueName, target.Address); } }; testPeer.ExpectSenderAttach(targetMatcher: targetMatcher, sourceMatcher: Assert.NotNull, senderSettled: false); ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge); IQueue queue = await session.GetQueueAsync(queueName); IMessageProducer producer = null; if (anonymousProducer) { producer = await session.CreateProducerAsync(); } else { producer = await session.CreateProducerAsync(queue); } byte priority = 5; String text = "myMessage"; testPeer.ExpectTransfer(messageMatcher: message => { if (setPriority) { Assert.IsFalse(message.Header.Durable); Assert.AreEqual(5, message.Header.Priority); } Assert.AreEqual(text, (message.BodySection as AmqpValue).Value); }, stateMatcher: Assert.IsNull, settled: false, sendResponseDisposition: true, responseState: new Accepted(), responseSettled: true); ITextMessage textMessage = await session.CreateTextMessageAsync(text); if (setOnProducer) { producer.DeliveryMode = MsgDeliveryMode.NonPersistent; if (setPriority) { producer.Priority = (MsgPriority)5; } if (anonymousProducer) { await producer.SendAsync(queue, textMessage); } else { await producer.SendAsync(textMessage); } } else { if (anonymousProducer) { await producer.SendAsync(destination : queue, message : textMessage, deliveryMode : MsgDeliveryMode.NonPersistent, priority : setPriority?(MsgPriority)priority : NMSConstants.defaultPriority, timeToLive : NMSConstants.defaultTimeToLive); } else { await producer.SendAsync(message : textMessage, deliveryMode : MsgDeliveryMode.NonPersistent, priority : setPriority?(MsgPriority)priority : NMSConstants.defaultPriority, timeToLive : NMSConstants.defaultTimeToLive); } } Assert.AreEqual(MsgDeliveryMode.NonPersistent, textMessage.NMSDeliveryMode, "Should have NonPersistent delivery mode set"); testPeer.WaitForAllMatchersToComplete(1000); testPeer.ExpectClose(); await connection.CloseAsync(); testPeer.WaitForAllMatchersToComplete(1000); } }
private async Task DoSendingMessageNonPersistentTestImpl(bool setPriority) { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { //Add capability to indicate support for ANONYMOUS-RELAY Symbol[] serverCapabilities = { SymbolUtil.OPEN_CAPABILITY_ANONYMOUS_RELAY }; var context = await EstablishNMSContextAsync(testPeer, serverCapabilities : serverCapabilities); testPeer.ExpectBegin(); string queueName = "myQueue"; Action <object> targetMatcher = t => { var target = t as Target; Assert.IsNotNull(target); }; testPeer.ExpectSenderAttach(targetMatcher: targetMatcher, sourceMatcher: Assert.NotNull, senderSettled: false); IQueue queue = await context.GetQueueAsync(queueName); INMSProducer producer = await context.CreateProducerAsync(); byte priority = 5; String text = "myMessage"; testPeer.ExpectTransfer(messageMatcher: message => { if (setPriority) { Assert.IsFalse(message.Header.Durable); Assert.AreEqual(priority, message.Header.Priority); } Assert.AreEqual(text, (message.BodySection as AmqpValue).Value); }, stateMatcher: Assert.IsNull, settled: false, sendResponseDisposition: true, responseState: new Accepted(), responseSettled: true); ITextMessage textMessage = await context.CreateTextMessageAsync(text); producer.DeliveryMode = MsgDeliveryMode.NonPersistent; if (setPriority) { producer.Priority = (MsgPriority)priority; } await producer.SendAsync(queue, textMessage); Assert.AreEqual(MsgDeliveryMode.NonPersistent, textMessage.NMSDeliveryMode, "Should have NonPersistent delivery mode set"); testPeer.WaitForAllMatchersToComplete(1000); testPeer.ExpectEnd(); testPeer.ExpectClose(); await context.CloseAsync(); testPeer.WaitForAllMatchersToComplete(1000); } }
void OnMessage(IMessage receivedMsg) { message = receivedMsg as ITextMessage; semaphore.Set(); }
protected static void OnMessage(IMessage receivedMsg) { _message = receivedMsg as ITextMessage; Semaphore.Set(); }
private static void consumer_Listener(IMessage message) { ITextMessage msg = (ITextMessage)message; Console.WriteLine(string.Format(@"接收到:{0}{1}", msg.Text, Environment.NewLine)); }
private static void consumer_Listener(IMessage message) { ITextMessage msg = message as ITextMessage; Console.WriteLine("Receive: " + msg.Text); }
public void SendMsg(string msg) { ITextMessage message = session.CreateTextMessage(msg); messageProducer.Send(message, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.FromDays(7)); }
private static void RunWithOptions(CommandLineOpts opts) { ITrace logger = new Logger(Logger.ToLogLevel(opts.logLevel)); Tracer.Trace = logger; string ip = opts.host; Uri providerUri = new Uri(ip); Console.WriteLine("scheme: {0}", providerUri.Scheme); StringDictionary properties = new StringDictionary(); if (opts.username != null) { properties["NMS.username"] = opts.username; } if (opts.password != null) { properties["NMS.password"] = opts.password; } if (opts.clientId != null) { properties["NMS.clientId"] = opts.clientId; } properties["NMS.sendtimeout"] = opts.connTimeout + ""; IConnection conn = null; if (opts.topic == null && opts.queue == null) { Console.WriteLine("ERROR: Must specify a topic or queue destination"); return; } try { Apache.NMS.AMQP.NMSConnectionFactory providerFactory = new Apache.NMS.AMQP.NMSConnectionFactory(providerUri, properties); IConnectionFactory factory = providerFactory.ConnectionFactory; Console.WriteLine("Creating Connection..."); conn = factory.CreateConnection(); conn.ExceptionListener += (logger as Logger).LogException; Console.WriteLine("Created Connection."); Console.WriteLine("Version: {0}", conn.MetaData); Console.WriteLine("Creating Session..."); ISession ses = conn.CreateSession(); Console.WriteLine("Session Created."); conn.Start(); IDestination dest = (opts.topic == null) ? (IDestination)ses.GetQueue(opts.queue) : (IDestination)ses.GetTopic(opts.topic); Console.WriteLine("Creating Message Producer for : {0}...", dest); IMessageProducer prod = ses.CreateProducer(dest); IMessageConsumer consumer = ses.CreateConsumer(dest); Console.WriteLine("Created Message Producer."); prod.DeliveryMode = opts.mode == 0 ? MsgDeliveryMode.NonPersistent : MsgDeliveryMode.Persistent; prod.TimeToLive = TimeSpan.FromSeconds(20); ITextMessage msg = prod.CreateTextMessage("Hello World!"); Console.WriteLine("Sending Msg: {0}", msg.ToString()); Console.WriteLine("Starting Connection..."); conn.Start(); Console.WriteLine("Connection Started: {0} Resquest Timeout: {1}", conn.IsStarted, conn.RequestTimeout); Console.WriteLine("Sending {0} Messages...", opts.NUM_MSG); for (int i = 0; i < opts.NUM_MSG; i++) { Tracer.InfoFormat("Sending Msg {0}", i + 1); // Text Msg Body msg.Text = "Hello World! n: " + i; prod.Send(msg); msg.ClearBody(); } IMessage rmsg = null; for (int i = 0; i < opts.NUM_MSG; i++) { Tracer.InfoFormat("Waiting to receive message {0} from consumer.", i); rmsg = consumer.Receive(TimeSpan.FromMilliseconds(opts.connTimeout)); if (rmsg == null) { Console.WriteLine("Failed to receive Message in {0}ms.", opts.connTimeout); } else { Console.WriteLine("Received Message with id {0} and contents {1}.", rmsg.NMSMessageId, rmsg.ToString()); } } if (conn.IsStarted) { Console.WriteLine("Closing Connection..."); conn.Close(); Console.WriteLine("Connection Closed."); } } catch (NMSException ne) { Console.WriteLine("Caught NMSException : {0} \nStack: {1}", ne.Message, ne); } catch (Exception e) { Console.WriteLine("Caught unexpected exception : {0}", e); } finally { if (conn != null) { conn.Dispose(); } } }
void SendMessage() { XMSFactoryFactory factoryFactory; IConnectionFactory cf; IConnection connectionWMQ; ISession sessionWMQ; IDestination destination; IDestination temporaryDestination; IMessageProducer producer; ITextMessage textMessage; // Get an instance of factory. factoryFactory = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ); // Create WMQ Connection Factory. cf = factoryFactory.CreateConnectionFactory(); // Set the properties cf.SetStringProperty(XMSC.WMQ_HOST_NAME, conn.host); Console.WriteLine("hostName is set {0, -20 }", conn.host); cf.SetIntProperty(XMSC.WMQ_PORT, conn.port); cf.SetStringProperty(XMSC.WMQ_CHANNEL, conn.channel); if (conn.key_repository != null && (conn.key_repository.Contains("*SYSTEM") || conn.key_repository.Contains("*USER"))) { cf.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT); } else { cf.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT_UNMANAGED); } cf.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, conn.qmgr); cf.SetStringProperty(XMSC.USERID, conn.app_user); cf.SetStringProperty(XMSC.PASSWORD, conn.app_password); cf.SetStringProperty(XMSC.WMQ_TEMPORARY_MODEL, conn.model_queue_name); if (conn.key_repository != null && conn.cipher_suite != null) { cf.SetStringProperty(XMSC.WMQ_SSL_KEY_REPOSITORY, conn.key_repository); } if (conn.cipher_suite != null) { cf.SetStringProperty(XMSC.WMQ_SSL_CIPHER_SPEC, conn.cipher_suite); } // Create connection. connectionWMQ = cf.CreateConnection(); Console.WriteLine("Connection created"); // Create session sessionWMQ = connectionWMQ.CreateSession(false, AcknowledgeMode.AutoAcknowledge); Console.WriteLine("Session created"); // Create destination destination = sessionWMQ.CreateQueue(conn.queue_name); destination.SetIntProperty(XMSC.WMQ_TARGET_CLIENT, XMSC.WMQ_TARGET_DEST_MQ); Console.WriteLine("Destination created"); // Create producer producer = sessionWMQ.CreateProducer(destination); Console.WriteLine("Producer created"); // Start the connection to receive messages. connectionWMQ.Start(); Console.WriteLine("Connection started"); // Create a text message and send it. textMessage = sessionWMQ.CreateTextMessage(); String corrID = xmsJson.correlationID; textMessage.Text = xmsJson.toJsonString(); //***disable for correl id by using message id textMessage.JMSCorrelationID = corrID; textMessage.JMSExpiration = 900000; temporaryDestination = sessionWMQ.CreateTemporaryQueue(); textMessage.JMSReplyTo = temporaryDestination; producer.Send(textMessage); Console.WriteLine("Message sent"); Console.WriteLine(textMessage.JMSCorrelationID); Console.WriteLine(corrID); String str = textMessage.JMSMessageID; String selector = "JMSCorrelationID='ID:" + JsonMessage.getCorrFilter(corrID) + "'"; Console.WriteLine(selector); IMessageConsumer consumer = sessionWMQ.CreateConsumer(temporaryDestination, selector); ITextMessage responseMessage = (ITextMessage)consumer.Receive(TIMEOUTTIME); if (responseMessage != null) { Console.WriteLine("Message received."); Console.Write(responseMessage); Console.WriteLine("\n"); } else { Console.WriteLine("Wait timed out."); } // Cleanup producer.Close(); destination.Dispose(); sessionWMQ.Dispose(); connectionWMQ.Close(); }
protected static void OnMessage(IMessage receivedMsg) { message = receivedMsg as ITextMessage; semaphore.Set(); }
private void consumer_Listener(IMessage message) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); ITextMessage msg = (ITextMessage)message; // 若收到的消息是空白的消息,在忽略 if (msg.Text.Trim() == "") { return; } string msgID = System.Guid.NewGuid().ToString("N"); Log( msgID, string.Format("收到的报文内容:[{0}]", msg.Text), strProcedureName); XmlDocument xml = new XmlDocument(); try { xml.LoadXml(msg.Text); } catch (Exception error) { Log( msgID, string.Format("解析报文时发生错误:[{0}]", error.Message), strProcedureName); return; } try { foreach (XmlNode node in xml.SelectNodes("ROOT/Row")) { xdr_MethodParams data = new xdr_MethodParams(); data.PartitioningKey = 600020000; data.ID = 0; data.CollectingTime = Tools.ConvertToInt64(node.Attributes["CollectingTime"].Value); data.EquipmentCode = node.Attributes["EquipmentCode"].Value; data.OperationCode = node.Attributes["OperationCode"].Value; data.StepNo = Tools.ConvertToInt32(node.Attributes["StepNo"].Value); data.ProductNo = node.Attributes["ProductNo"].Value; data.LotNumber = node.Attributes["LotNumber"].Value; data.SerialNumber = node.Attributes["SerialNumber"].Value; data.Ordinal = Tools.ConvertToInt32(node.Attributes["Ordinal"].Value); data.ParamCode = node.Attributes["ParamCode"].Value; data.ParamName = node.Attributes["ParamName"].Value; data.Remark = ""; if (node.NodeType == XmlNodeType.CDATA || node.NodeType == XmlNodeType.Text) { data.Remark = node.Value; } if (node.Attributes["Remark"] != null) { data.Remark = node.Attributes["Remark"].Value; } data.CollectMode = 0; data.LowLimit = Tools.ConvertToInt64(node.Attributes["LowLimit"].Value); data.Criterion = node.Attributes["Criterion"].Value; data.HighLimit = Tools.ConvertToInt64(node.Attributes["HighLimit"].Value); data.Scale = Tools.ConvertToInt32(node.Attributes["Scale"].Value); data.UnitOfMeasure = node.Attributes["UnitOfMeasure"].Value; data.Conclusion = node.Attributes["Conclusion"].Value; data.Metric01 = Tools.ConvertToInt64(node.Attributes["Metric01"].Value); data.Metric02 = Tools.ConvertToInt64(node.Attributes["Metric02"].Value); data.Metric03 = Tools.ConvertToInt64(node.Attributes["Metric03"].Value); data.Metric04 = Tools.ConvertToInt64(node.Attributes["Metric04"].Value); data.Metric05 = Tools.ConvertToInt64(node.Attributes["Metric05"].Value); try { string sqlCmd = "INSERT INTO IRAPDPA..xdr_MethodParams" + "(PartitioningKey, CollectingTime, EquipmentCode, " + "OperationCode, StepNo, ProductNo, LotNumber, " + "SerialNumber, Ordinal, ParamCode, ParamName, " + "Remark, CollectMode, LowLimit, Criterion, HighLimit, " + "Scale, UnitOfMeasure, Conclusion, Metric01, " + "Metric02, Metric03, Metric04, Metric05) " + "VALUES(@PartitioningKey, @CollectingTime, @EquipmentCode, " + "@OperationCode, @StepNo, @ProductNo, @LotNumber, " + "@SerialNumber, @Ordinal, @ParamCode, @ParamName, " + "@Remark, @CollectMode, @LowLimit, @Criterion, @HighLimit, " + "@Scale, @UnitOfMeasure, @Conclusion, @Metric01, " + "@Metric02, @Metric03, @Metric04, @Metric05)"; SqlCommand cmd = new SqlCommand(sqlCmd, dbConnection); cmd.Parameters.Add(new SqlParameter("@PartitioningKey", SqlDbType.BigInt) { Value = data.PartitioningKey }); cmd.Parameters.Add(new SqlParameter("@CollectingTime", SqlDbType.BigInt) { Value = data.CollectingTime }); cmd.Parameters.Add(new SqlParameter("@EquipmentCode", SqlDbType.VarChar, 40) { Value = data.EquipmentCode }); cmd.Parameters.Add(new SqlParameter("@OperationCode", SqlDbType.VarChar, 40) { Value = data.OperationCode }); cmd.Parameters.Add(new SqlParameter("@StepNo", SqlDbType.Int) { Value = data.StepNo }); cmd.Parameters.Add(new SqlParameter("@ProductNo", SqlDbType.VarChar, 40) { Value = data.ProductNo }); cmd.Parameters.Add(new SqlParameter("@LotNumber", SqlDbType.VarChar, 50) { Value = data.LotNumber }); cmd.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.VarChar, 80) { Value = data.SerialNumber }); cmd.Parameters.Add(new SqlParameter("@Ordinal", SqlDbType.Int) { Value = data.Ordinal }); cmd.Parameters.Add(new SqlParameter("@ParamCode", SqlDbType.VarChar, 40) { Value = data.ParamCode }); cmd.Parameters.Add(new SqlParameter("@ParamName", SqlDbType.NVarChar, 100) { Value = data.ParamName }); cmd.Parameters.Add(new SqlParameter("@Remark", SqlDbType.VarChar, 2147483647) { Value = data.Remark }); cmd.Parameters.Add(new SqlParameter("@CollectMode", SqlDbType.TinyInt) { Value = data.CollectMode }); cmd.Parameters.Add(new SqlParameter("@LowLimit", SqlDbType.BigInt) { Value = data.LowLimit }); cmd.Parameters.Add(new SqlParameter("@Criterion", SqlDbType.VarChar, 4) { Value = data.Criterion }); cmd.Parameters.Add(new SqlParameter("@HighLimit", SqlDbType.BigInt) { Value = data.HighLimit }); cmd.Parameters.Add(new SqlParameter("@Scale", SqlDbType.SmallInt) { Value = data.Scale }); cmd.Parameters.Add(new SqlParameter("@UnitOfMeasure", SqlDbType.NVarChar, 20) { Value = data.UnitOfMeasure }); cmd.Parameters.Add(new SqlParameter("@Conclusion", SqlDbType.VarChar, 1) { Value = data.Conclusion }); cmd.Parameters.Add(new SqlParameter("@Metric01", SqlDbType.BigInt) { Value = data.Metric01 }); cmd.Parameters.Add(new SqlParameter("@Metric02", SqlDbType.BigInt) { Value = data.Metric02 }); cmd.Parameters.Add(new SqlParameter("@Metric03", SqlDbType.BigInt) { Value = data.Metric03 }); cmd.Parameters.Add(new SqlParameter("@Metric04", SqlDbType.BigInt) { Value = data.Metric04 }); cmd.Parameters.Add(new SqlParameter("@Metric05", SqlDbType.BigInt) { Value = data.Metric05 }); cmd.ExecuteNonQuery(); Log(msgID, "插表成功", strProcedureName); } catch (Exception error) { Log( msgID, string.Format( "插表时发生错误:{0}", error.Message), strProcedureName); } } } finally { } }
public static void Main(string[] args) { // Example connection strings: // activemq:tcp://activemqhost:61616 // activemq:tcp://activemqhost:61613?transport.wireformat=stomp // ems:tcp://tibcohost:7222 // msmq://localhost Uri connecturi = new Uri("activemq:tcp://activemqhost: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"); // IDestination destination = session.GetTopic("FOO.BAR"); // // Embedded destination type in the name: // IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR"); // IDestination destination = SessionUtil.GetDestination(session, "topic://FOO.BAR"); // // Defaults to queue if type is not specified: // IDestination destination = SessionUtil.GetDestination(session, "FOO.BAR"); IDestination destination = SessionUtil.GetDestination(session, "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)) { connection.Start(); // Must start the connection for async messaging. producer.Persistent = true; 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); // Wait for the message semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true); 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); } } } }
public void TestReceiveMessageAsyncClientAck() { const int NUM_MSGS = 100; const int MESSAGE_RECEIVE_TIMEOUT = 1000; // 1.0s //Apache.NMS.Util.Atomic<bool> stopped = new Apache.NMS.Util.Atomic<bool>(false); using (IConnection connection = this.GetConnection()) using (ISession session = this.GetSession("default")) using (IMessageConsumer consumer = this.GetConsumer("con1")) using (IMessageProducer producer = this.GetProducer("pro1")) { try { Assert.AreEqual(AcknowledgementMode.ClientAcknowledge, session.AcknowledgementMode, "Session acknowkedgement mode is not Client mode."); MessageListener ackcallback = CreateListener(NUM_MSGS); MessageListener callback = (m) => { if (!connection.IsStarted) { waiter.Set(); throw new Exception("Received Message " + msgCount + " on stopped connection."); } m.Properties["NMS.AMQP.ACK.TYPE"] = 0; // AMQP Accepted m.Acknowledge(); ackcallback(m); Logger.Info("MsgCount : " + msgCount); }; consumer.Listener += callback; connection.ExceptionListener += DefaultExceptionListener; connection.Start(); ITextMessage message = producer.CreateTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.Text = "num:" + i; producer.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.Zero); } if (!waiter.WaitOne(MESSAGE_RECEIVE_TIMEOUT)) { Assert.IsNull(asyncEx, "OnExceptionListener Event when raised. Message : {0}.", asyncEx?.Message); Assert.Fail("Received {0} of {1} messages in {2}ms.", msgCount, NUM_MSGS, MESSAGE_RECEIVE_TIMEOUT); } Assert.IsNull(asyncEx, "OnExceptionListener Event when raised. Message : {0}.", asyncEx?.Message); Assert.AreEqual(NUM_MSGS, msgCount, "Failed to Received All Messages sent."); } catch (Exception ex) { if (asyncEx != null) { Logger.Warn("Async execption: " + this.GetTestException(asyncEx)); } this.PrintTestFailureAndAssert(this.GetMethodName(), "Unexpected Exception.", ex); } } }
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 = SessionUtil.GetDestination(session, "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); } } } }
public void TestSubscriptionDurabilityOverConnections() { const int MSG_BATCH_SIZE = 100; const int TIMEOUT = 1000 * MSG_BATCH_SIZE; const string MSG_BATCH_ID_PROP_KEY = "batch_id"; string subName = DURABLE_SUBSRIPTION_NAME; ITopic topic = this.GetDestination("t1") as ITopic; int msgSentCount = 0; bool cleaned = false; try { string clientId = null; IMessageProducer producer = this.GetProducer("sender"); ITextMessage sendMsg = producer.CreateTextMessage(); using (IConnection initialConnection = this.GetConnection("c1")) { initialConnection.ExceptionListener += DefaultExceptionListener; clientId = initialConnection.ClientId; // create subscription ISession subFactory = this.GetSession("s1"); IMessageConsumer durableConsumer = subFactory.CreateDurableConsumer(topic, subName, null, false); durableConsumer.Listener += CreateListener(MSG_BATCH_SIZE); // send messages to subscription for (int i = 0; i < MSG_BATCH_SIZE; i++) { sendMsg.Text = String.Format("msg : {0}", msgSentCount); sendMsg.Properties.SetInt(MSG_BATCH_ID_PROP_KEY, i); producer.Send(sendMsg); msgSentCount++; } initialConnection.Start(); // assert messages are received Assert.IsTrue(this.waiter.WaitOne(TIMEOUT), "Timed out waiting to receive messages, received {0} of {1} in {2}ms", msgCount, msgSentCount, TIMEOUT); Assert.IsNull(asyncEx, "Caught asynchronous exception. {0}", asyncEx?.ToString()); Assert.AreEqual(msgSentCount, msgCount, "Messages sent do not match messages received"); } // initial connection is closed and the subscription is inactive. // send more messages to the subscription. for (int i = 0; i < MSG_BATCH_SIZE; i++) { sendMsg.Text = String.Format("msg : {0}", msgSentCount); sendMsg.Properties.SetInt(MSG_BATCH_ID_PROP_KEY, i); producer.Send(sendMsg); msgSentCount++; } this.waiter.Reset(); // re-activate the subscription using (IConnection connection = this.GetConnection("c2")) { connection.ClientId = clientId; connection.ExceptionListener += DefaultExceptionListener; ISession subscriptionFactory = connection.CreateSession(); IMessageConsumer durableConsumer = subscriptionFactory.CreateDurableConsumer(topic, subName, null, false); durableConsumer.Listener += CreateListener(MSG_BATCH_SIZE * 2); connection.Start(); // assert messages sent while inactive are received Assert.IsTrue(this.waiter.WaitOne(TIMEOUT), "Timed out waiting to receive messages, received {0} of {1} in {2}ms", msgCount, msgSentCount, TIMEOUT); Assert.IsNull(asyncEx, "Caught asynchronous exception. {0}", asyncEx?.ToString()); Assert.AreEqual(msgSentCount, msgCount, "Messages sent while inactive do not match messages received"); // unsubscribe durableConsumer.Close(); subscriptionFactory.DeleteDurableConsumer(subName); durableConsumer = null; cleaned = true; } } catch (Exception ex) { this.PrintTestFailureAndAssert(this.GetTestMethodName(), "Unexpected Exception.", ex); } finally { // clean up code to prevent leaving a durbale subscription on the test broker. if (!cleaned) { try { this.GetSession("s2").DeleteDurableConsumer(subName); } catch (InvalidDestinationException ide) { Logger.Info(string.Format("Unable to unsubscribe from {0}, Cause : {1}", subName, ide)); } catch (Exception ex) { Logger.Warn(string.Format("Caught unexpected failure while unsubscribing from {0}. Failure : {1}", subName, ex)); } } } }
public void TestDurableConsumerSelectorChange( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode) { try { using (IConnection connection = CreateConnection(TEST_CLIENT_AND_CONSUMER_ID)) { connection.Start(); using (ISession session = connection.CreateSession(ackMode)) { ITopic topic = (ITopic)CreateDestination(session, DestinationType.Topic); IMessageProducer producer = session.CreateProducer(topic); IMessageConsumer consumer = session.CreateDurableConsumer(topic, TEST_CLIENT_AND_CONSUMER_ID, "color='red'", false); producer.DeliveryMode = MsgDeliveryMode.Persistent; // Send the messages ITextMessage sendMessage = session.CreateTextMessage("1st"); sendMessage.Properties["color"] = "red"; producer.Send(sendMessage); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } ITextMessage receiveMsg = consumer.Receive(receiveTimeout) as ITextMessage; Assert.IsNotNull(receiveMsg, "Failed to retrieve 1st durable message."); Assert.AreEqual("1st", receiveMsg.Text); Assert.AreEqual(MsgDeliveryMode.Persistent, receiveMsg.NMSDeliveryMode, "NMSDeliveryMode does not match"); receiveMsg.Acknowledge(); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } // Change the subscription, allowing some time for the Broker to purge the // consumers resources. consumer.Dispose(); Thread.Sleep(1000); consumer = session.CreateDurableConsumer(topic, TEST_CLIENT_AND_CONSUMER_ID, "color='blue'", false); sendMessage = session.CreateTextMessage("2nd"); sendMessage.Properties["color"] = "red"; producer.Send(sendMessage); sendMessage = session.CreateTextMessage("3rd"); sendMessage.Properties["color"] = "blue"; producer.Send(sendMessage); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } // Selector should skip the 2nd message. receiveMsg = consumer.Receive(receiveTimeout) as ITextMessage; Assert.IsNotNull(receiveMsg, "Failed to retrieve durable message."); Assert.AreEqual("3rd", receiveMsg.Text, "Retrieved the wrong durable message."); Assert.AreEqual(MsgDeliveryMode.Persistent, receiveMsg.NMSDeliveryMode, "NMSDeliveryMode does not match"); receiveMsg.Acknowledge(); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } // Make sure there are no pending messages. Assert.IsNull(consumer.ReceiveNoWait(), "Wrong number of messages in durable subscription."); } } } catch (Exception ex) { Assert.Fail(ex.Message); } finally { // Pause to allow Stomp to unregister at the broker. Thread.Sleep(500); UnregisterDurableConsumer(TEST_CLIENT_AND_CONSUMER_ID, TEST_CLIENT_AND_CONSUMER_ID); } }
protected void AssertTextMessageEqual(ITextMessage m1, ITextMessage m2, string message) { Assert.IsFalse(m1 == null ^ m2 == null, message + ": expected {" + m1 + "}, but was {" + m2 + "}"); if(m1 == null) { return; } Assert.AreEqual(m1.Text, m2.Text, message); }
public void TestSendWhileClosed( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode) { try { using (IConnection connection = CreateConnection(TEST_CLIENT_AND_CONSUMER_ID)) { connection.Start(); using (ISession session = connection.CreateSession(ackMode)) { ITopic topic = (ITopic)CreateDestination(session, DestinationType.Topic); IMessageProducer producer = session.CreateProducer(topic); producer.DeliveryMode = MsgDeliveryMode.Persistent; ISession consumeSession = connection.CreateSession(ackMode); IMessageConsumer consumer = consumeSession.CreateDurableConsumer(topic, TEST_CLIENT_AND_CONSUMER_ID, null, false); Thread.Sleep(1000); consumer.Dispose(); consumer = null; ITextMessage message = session.CreateTextMessage("DurableTest-TestSendWhileClosed"); message.Properties.SetString("test", "test"); message.NMSType = "test"; producer.Send(message); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } Thread.Sleep(1000); consumer = consumeSession.CreateDurableConsumer(topic, TEST_CLIENT_AND_CONSUMER_ID, null, false); ITextMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)) as ITextMessage; msg.Acknowledge(); if (AcknowledgementMode.Transactional == ackMode) { consumeSession.Commit(); } Assert.IsNotNull(msg); Assert.AreEqual(msg.Text, "DurableTest-TestSendWhileClosed"); Assert.AreEqual(msg.NMSType, "test"); Assert.AreEqual(msg.Properties.GetString("test"), "test"); } } } catch (Exception ex) { Assert.Fail(ex.Message); } finally { // Pause to allow Stomp to unregister at the broker. Thread.Sleep(500); UnregisterDurableConsumer(TEST_CLIENT_AND_CONSUMER_ID, TEST_CLIENT_AND_CONSUMER_ID); } }
public void TestMultipleProducerCreateAndSend( [Values(MsgDeliveryMode.NonPersistent, MsgDeliveryMode.Persistent)] MsgDeliveryMode mode ) { const int MSG_TTL_MILLIS = 8500; // 8.5 secs const int NUM_MSGS = 200; const int NUM_PRODUCERS = 5; const string MSG_ID_KEY = "MsgIndex"; const string PRODUCER_ID_KEY = "ProducerIndex"; const string PRODUCER_INDEXED_ID_KEY = "ProducerIndexedMsgId"; bool persistent = mode.Equals(MsgDeliveryMode.Persistent); bool useMsgId = !persistent; int msgIdWindow = 0; string failureErr = null; IMessageProducer producer = null; IList <IMessageProducer> producers = null; IList <int> lastProducerIndexedIds = null; try { using (IConnection connection = this.GetConnection("c1")) using (ISession session = this.GetSession("s1")) using (IDestination destination = this.GetDestination("t1")) using (IMessageConsumer drain = this.GetConsumer("drain")) { lastProducerIndexedIds = new List <int>(); MessageListener ackCallback = CreateListener(NUM_MSGS); drain.Listener += (message) => { if (failureErr == null) { ackCallback(message); int id = message.Properties.GetInt(PRODUCER_INDEXED_ID_KEY); int prodIndex = message.Properties.GetInt(PRODUCER_ID_KEY); int lastId = lastProducerIndexedIds[prodIndex]; int advancedMsgs = id - lastId; if (id < lastId) { failureErr = string.Format( "Received message out of order." + " Received, sent from producer {0} msg id {1} where last msg id {2}", prodIndex, id, lastId ); this.waiter.Set(); } else if (persistent && advancedMsgs > 1) { failureErr = string.Format( "Persistent Messages where drop." + " Received, sent from producer {0} msg id {1} where last msg id {2}", prodIndex, id, lastId ); this.waiter.Set(); } else { lastProducerIndexedIds[prodIndex] = id; if (advancedMsgs > 1 && (Logger.IsInfoEnabled || Logger.IsDebugEnabled)) { Logger.Info(string.Format( "{0} Messages dropped for producer {1} from message id {2}", advancedMsgs, prodIndex, lastId )); } msgIdWindow += advancedMsgs; if (!persistent && msgIdWindow == NUM_MSGS) { this.waiter.Set(); } } } }; connection.ExceptionListener += DefaultExceptionListener; producers = new List <IMessageProducer>(); for (int i = 0; i < NUM_PRODUCERS; i++) { try { producer = session.CreateProducer(destination); } catch (Exception ex) { this.PrintTestFailureAndAssert(this.GetMethodName(), "Failed to Created Producer " + i, ex); } producer.DeliveryMode = mode; producer.DisableMessageID = !useMsgId; producer.TimeToLive = TimeSpan.FromMilliseconds(MSG_TTL_MILLIS); producers.Add(producer); lastProducerIndexedIds.Add(-1); } connection.Start(); Assert.AreEqual(NUM_PRODUCERS, producers.Count, "Did not create all producers."); Assert.IsNull(asyncEx, "Exception Listener Called While creating producers. With exception {0}.", asyncEx); ITextMessage msg = session.CreateTextMessage(); int producerIndex = -1; for (int i = 0; i < NUM_MSGS; i++) { msg.Text = "Index:" + i; msg.Properties[MSG_ID_KEY] = i; msg.Properties[PRODUCER_INDEXED_ID_KEY] = i / NUM_PRODUCERS; producerIndex = i % NUM_PRODUCERS; msg.Properties[PRODUCER_ID_KEY] = producerIndex; producers[producerIndex].Send(msg); } Assert.IsNull(asyncEx, "Exception Listener Called While sending messages. With exception {0}.", asyncEx); Assert.IsTrue(waiter.WaitOne(TIMEOUT), "Failed to received all messages in {0}ms. Received {1} of {2} messages", TIMEOUT, msgCount, NUM_MSGS); Assert.IsNull(failureErr, "Received assertion failure from IMessageConsumer message Listener. Failure : {0}", failureErr ?? ""); if (persistent) { Assert.AreEqual(NUM_MSGS, msgCount, "Receive unexpected from messages sent. Message Window {0}", msgIdWindow); } else { int missedMsgs = (msgIdWindow - msgCount); Assert.AreEqual(NUM_MSGS, msgIdWindow, "Failed to receive all messages." + " Received {0} of {1} messages, with missed messages {2}, in {3}ms", msgCount, NUM_MSGS, missedMsgs, TIMEOUT ); if (missedMsgs > 0) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); const string SEPARATOR = ", "; for (int i = 0; i < NUM_PRODUCERS; i++) { sb.AppendFormat("Last received Producer {0} message id {1}{2}", i, lastProducerIndexedIds[i], SEPARATOR); } sb.Length = sb.Length - SEPARATOR.Length; Logger.Warn(string.Format("Did not receive all Non Persistent messages. Received {0} of {1} messages. Where last received message ids = [{2}]", msgCount, NUM_MSGS, sb.ToString())); } } Assert.IsNull(asyncEx, "Exception Listener Called While receiveing messages. With exception {0}.", asyncEx); // // Some brokers are sticklers for detail and actually honor the // batchable flag that AMQPnetLite sets on all published messages. As // a result all messages can be long received before the published // messages are acknowledged. So to avoid a hand full of // amqp:message:released outcomes, just pause a few seconds before // closing the producer System.Threading.Thread.Sleep(3000); } } catch (Exception e) { this.PrintTestFailureAndAssert(this.GetMethodName(), "Unexpected Exception.", e); } finally { if (producers != null) { foreach (IMessageProducer p in producers) { p?.Close(); p?.Dispose(); } producers.Clear(); } } }
private void TestDestinationMessageDelivery( IConnection connection, ISession session, IMessageProducer producer, IDestination destination, int msgPoolSize, bool isDurable = false) { bool cleaned = !isDurable; const string PROP_KEY = "send_msg_id"; string subName = DURABLE_SUBSRIPTION_NAME; int TotalMsgSent = 0; int TotalMsgRecv = 0; MsgDeliveryMode initialMode = producer.DeliveryMode; try { IMessageConsumer consumer = isDurable ? session.CreateDurableConsumer(destination as ITopic, subName, null, false) : session.CreateConsumer(destination); ITextMessage sendMessage = session.CreateTextMessage(); consumer.Listener += CreateListener(msgPoolSize); connection.ExceptionListener += DefaultExceptionListener; connection.Start(); for (int i = 0; i < msgPoolSize; i++) { sendMessage.Text = "Msg:" + i; sendMessage.Properties.SetInt(PROP_KEY, TotalMsgSent); producer.Send(sendMessage); TotalMsgSent++; } bool signal = waiter.WaitOne(TIMEOUT); TotalMsgRecv = msgCount; Assert.IsTrue(signal, "Timed out waiting to receive messages. Received {0} of {1} in {2}ms.", msgCount, TotalMsgSent, TIMEOUT); Assert.AreEqual(TotalMsgSent, msgCount, "Failed to receive all messages. Received {0} of {1} in {2}ms.", msgCount, TotalMsgSent, TIMEOUT); // close consumer consumer.Close(); // reset waiter waiter.Reset(); for (int i = 0; i < msgPoolSize; i++) { sendMessage.Text = "Msg:" + i; sendMessage.Properties.SetInt(PROP_KEY, TotalMsgSent); producer.Send(sendMessage); TotalMsgSent++; if (isDurable || destination.IsQueue) { TotalMsgRecv++; } } // Must stop connection before we can add a consumer connection.Stop(); int expectedId = (isDurable || destination.IsQueue) ? msgPoolSize : TotalMsgSent; // expectedMsgCount is 2 msgPoolSize groups for non-durable topics, one for initial send of pool size and one for final send of pool size. // expedtedMsgCount is 3 msgPoolSize groups for queues and durable topics, same two groups for non-durable topic plus the group sent while there is no active consumer. int expectedMsgCount = (isDurable || destination.IsQueue) ? 3 * msgPoolSize : 2 * msgPoolSize; MessageListener callback = CreateListener(expectedMsgCount); string errString = null; consumer = consumer = isDurable ? session.CreateDurableConsumer(destination as ITopic, subName, null, false) : session.CreateConsumer(destination); consumer.Listener += (m) => { int id = m.Properties.GetInt(PROP_KEY); if (id != expectedId) { errString = string.Format("Received Message with unexpected msgId. Received msg : {0} Expected : {1}", id, expectedId); waiter.Set(); return; } else { expectedId++; } callback(m); }; // Start Connection connection.Start(); for (int i = 0; i < msgPoolSize; i++) { sendMessage.Text = "Msg:" + i; sendMessage.Properties.SetInt(PROP_KEY, TotalMsgSent); producer.Send(sendMessage); TotalMsgSent++; TotalMsgRecv++; } signal = waiter.WaitOne(TIMEOUT); Assert.IsNull(asyncEx, "Received asynchrounous exception. Message: {0}", asyncEx?.Message); Assert.IsNull(errString, "Failure occured on Message Callback. Message : {0}", errString ?? ""); Assert.IsTrue(signal, "Timed out waiting for message receive. Received {0} of {1} in {2}ms.", msgCount, TotalMsgRecv, TIMEOUT); Assert.AreEqual(TotalMsgRecv, msgCount, "Failed to receive all messages. Received {0} of {1} in {2}ms.", msgCount, TotalMsgRecv, TIMEOUT); connection.Stop(); consumer.Close(); } catch (Exception ex) { this.PrintTestFailureAndAssert(this.GetTestMethodName(), "Unexpected Exception", ex); } finally { if (!cleaned) { try { session.DeleteDurableConsumer(subName); } catch (InvalidDestinationException ide) { Logger.Info(string.Format("Unable to unsubscribe from {0}, Cause : {1}", subName, ide)); } catch (Exception ex) { Logger.Warn(string.Format("Caught unexpected failure while unsubscribing from {0}. Failure : {1}", subName, ex)); } } } }
private InvalidationInformation GetInvalidationInformation(ITextMessage message) { XElement xml = null; try { xml = XElement.Parse(message.Text); } catch (Exception) { Logger.Error("Unable to parse invalidation xml!. Returning an empty collection. Nothing is invalidated!"); //throw new Exception(); return new InvalidationInformation(); } var invalidationInformation = new InvalidationInformation(); //Get all pages to invalidate Logger.Debug(string.Format("XML invalidation message: ", xml.ToString())); var allPageUrls = xml.Descendants().Where(e => e.Name.LocalName.Equals("url")).ToList(); if (allPageUrls.Any()) { var urlInfo = allPageUrls.Select(urlElem => new InvalidationUrl { Url = urlElem.Value, PublicationId = int.Parse(urlElem.Attribute("pubId").Value), TcmUri = string.Format("tcm:{0}-{1}-64", urlElem.Attribute("pubId").Value, urlElem.Attribute("itemId").Value) }).Cast<IInvalidationUrl>().ToList(); //return new InvalidationInformation { InvalidationUrls = urlInfo }; invalidationInformation.InvalidationUrls = urlInfo; } return invalidationInformation; }
public void TestTemporaryTopicReplyTo() { const int NUM_MSGS = 100; const string MSG_BODY = "num : "; IDestination replyTo = GetDestination("temp1"); long repliedCount = 0; long lastRepliedId = -1; string errString = null; CountDownLatch replierFinished = new CountDownLatch(NUM_MSGS); using (IConnection connection = GetConnection("c1")) using (IMessageConsumer receiver = GetConsumer("receiver")) using (IMessageConsumer listener = GetConsumer("listener")) using (IMessageProducer sender = GetProducer("sender")) using (IMessageProducer replyer = GetProducer("replyer")) { try { connection.ExceptionListener += DefaultExceptionListener; ITextMessage rmsg = null; ITextMessage sendMsg = sender.CreateTextMessage(); sendMsg.NMSReplyTo = replyTo; listener.Listener += (message) => { if (errString == null) { repliedCount++; long msgId = ExtractMsgId(message.NMSMessageId); if (msgId != lastRepliedId + 1) { // Test failed release blocked thread for shutdown. errString = String.Format("Received msg {0} out of order expected {1}", msgId, lastRepliedId + 1); waiter.Set(); } else { lastRepliedId = msgId; if (msgId == NUM_MSGS - 1) { message.Acknowledge(); // test done signal complete. waiter.Set(); return; } message.Acknowledge(); } } }; receiver.Listener += (message) => { if (errString == null) { msgCount++; rmsg = message as ITextMessage; if (rmsg == null) { // test failure errString = string.Format( "Received message, id = {2}, body of type {0}, expected {1}.", message.GetType().Name, typeof(ITextMessage).Name, ExtractMsgId(message.NMSMessageId) ); waiter.Set(); return; } IDestination replyDestination = message.NMSReplyTo; if (!replyDestination.Equals(replyTo)) { // test failure errString = string.Format( "Received message, id = {0}, with incorrect reply Destination. Expected : {1}, Actual : {2}.", ExtractMsgId(message.NMSMessageId), replyTo, replyDestination ); waiter.Set(); return; } else { ITextMessage reply = replyer.CreateTextMessage(); reply.Text = "Received:" + rmsg.Text; try { replyer.Send(reply); replierFinished.countDown(); } catch (NMSException nEx) { Logger.Error("Failed to send message from replyer Cause : " + nEx); throw nEx; } } } }; connection.Start(); for (int i = 0; i < NUM_MSGS; i++) { sendMsg.Text = MSG_BODY + i; sender.Send(sendMsg); } // allow for two seconds for each message to be sent and replied to. int timeout = 2000 * NUM_MSGS; if (!waiter.WaitOne(timeout)) { Assert.Fail("Timed out waiting on message delivery to complete. Received {1} of {0}, Replied {2} of {0}, Last Replied Msg Id {3}.", NUM_MSGS, msgCount, repliedCount, lastRepliedId); } else if (errString != null) { Assert.Fail("Asynchronous failure occurred. Cause : {0}", errString); } else { Assert.IsTrue(replierFinished.await(TimeSpan.FromMilliseconds(timeout)), "Replier thread has not finished sending messages. Remaining {0}", replierFinished.Remaining); Assert.IsNull(asyncEx, "Received Exception Asynchronously. Cause : {0}", asyncEx); Assert.AreEqual(NUM_MSGS, msgCount, "Failed to receive all messages."); Assert.AreEqual(NUM_MSGS, repliedCount, "Failed to reply to all messages"); Assert.AreEqual(NUM_MSGS - 1, lastRepliedId, "Failed to receive the final message"); } } catch (Exception ex) { this.PrintTestFailureAndAssert(GetTestMethodName(), "Unexpected exception.", ex); } } }
/// <summary> Extract a String from the given ITextMessage.</summary> /// <param name="message">the message to convert /// </param> /// <returns> the resulting String /// </returns> /// <throws> NMSException if thrown by NMS methods </throws> protected virtual string ExtractStringFromMessage(ITextMessage message) { return message.Text; }
public void TestSendToTemporaryOnClosedSession() { const int NUM_MSGS = 100; string errString = null; const int TIMEOUT = NUM_MSGS * 100; try { using (IConnection connection = GetConnection("c1")) using (ISession tFactory = GetSession("tFactory")) using (IMessageProducer producer = GetProducer("sender")) using (IMessageConsumer consumer = GetConsumer("receiver")) { IDestination destination = GetDestination("temp"); ITextMessage sendMessage = producer.CreateTextMessage(); MessageListener ackCallback = CreateListener(NUM_MSGS); MessageListener callback = (message) => { if (errString == null) { if (!destination.Equals(message.NMSReplyTo)) { errString = string.Format("Received message, id = {0}, has incorrect ReplyTo property.", ExtractMsgId(message.NMSMessageId)); waiter.Set(); } ackCallback(message); } }; consumer.Listener += callback; connection.ExceptionListener += DefaultExceptionListener; sendMessage.NMSReplyTo = destination; connection.Start(); // close session tFactory.Close(); for (int i = 0; i < NUM_MSGS; i++) { sendMessage.Text = string.Format("Link:{0},count:{1}", "temp", i); producer.Send(sendMessage); sendMessage.ClearBody(); } if (!waiter.WaitOne(TIMEOUT)) { if (errString == null) { Assert.Fail("Timed out waiting messages. Received, {0} of {1} messages in {2}ms.", msgCount, NUM_MSGS, TIMEOUT); } else { Assert.Fail(errString); } } Assert.AreEqual(NUM_MSGS, msgCount, "Did not receive expected number of messages."); } } catch (Exception ex) { this.PrintTestFailureAndAssert(GetTestMethodName(), "Unexpected exception.", ex); } }
private Type GetTargetType(ITextMessage message) { return typeMapper.ToType(message.Properties.GetString(typeMapper.TypeIdFieldName)); }
public void enviarMensaje(string text) { ITextMessage objecto = _producer.CreateTextMessage(text); _producer.Send(objecto); }
/// <summary> /// Serialize the object as XML into the Text body of the message. /// Set the NMSType to the full name of the object type. /// </summary> /// <param name="message"></param> /// <param name="obj"></param> /// <returns></returns> internal static ITextMessage SerializeObjToMessage(ITextMessage message, object obj) { // Embed the type into the message message.NMSType = obj.GetType().FullName; message.Text = XmlUtil.Serialize(obj); return message; }
public void Send(string message) { try { var connection = Connection; var session = connection.CreateSession(); _request = session.CreateTextMessage(message); _destination = SessionUtil.GetDestination(session, "queue://" + Queue); _producer = session.CreateProducer(_destination); if (!stopped) _producer.Send(_request); } catch (Apache.NMS.ActiveMQ.BrokerException) { Reset(); System.Threading.Thread.Sleep(5000); } catch (ThreadAbortException tae) { // catch debugging exceptions only when a debugger is attached. Console.WriteLine(tae); } catch { Reset(); } }