ACTIVEMQ Another mode of Sub/hub that is the publish subscription mode, is the Sub/hub is a drag n the meaning of the USB splitter. It means that a source is divided into n exits. As an example of the previous section, when an order is generated, the background n systems need to be linked, but there is a prerequisite to receive order information, then we need to publish a producer's message to n consumers.
Producers:
try {//create the Connection Factory iconnectionfactory Factory = New ConnectionFactory ("tcp://localhost:61616/"); using (iconnection connection = factory. CreateConnection ()) {//create the session using (ISession session = connection. CreateSession ()) {//create The Producer for the Topic/queue Imessageproducer prod = session. Createproducer (New Apache.NMS.ActiveMQ.Commands.ActiveMQTopic ("testing")); Send Messages int i = 0; while (! console.keyavailable) {itextmessage msg = prod. Createtextmessage (); Msg. Text = i.ToString (); Console.WriteLine ("Sending:" + i.tostring ()); Prod. Send (msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, Timespan.minvalue); System.Threading.Thread.Sleep (5000); i++; }}} console.readline (); } catch (System.Exception e) {Console.WriteLine ("{0}", e.message); Console.ReadLine (); }
Suppose the producer sends a message every 5 seconds:
Consumers:
static void Main (string[] args) {try {//create the Connection FA Ctory Iconnectionfactory factory = new ConnectionFactory ("tcp://localhost:61616/"); Create the connection using (iconnection connection = factory. CreateConnection ()) {connection. ClientId = "Testing Listener1"; Connection. Start (); Create the session using (ISession session = connection. CreateSession ()) {//create the Consumer Imessageco Nsumer consumer = session. Createdurableconsumer (New Apache.NMS.ActiveMQ.Commands.ActiveMQTopic ("testing"), "testing Listener1", NULL, FALSE); Consumer. Listener + = new MessageListener (Consumer_listener); Console.readLine (); } connection. Stop (); Connection. Close (); }} catch (System.Exception e) {Console.WriteLine (e.message); }} static void Consumer_listener (IMessage message) {try {itextmessage msg = (itextmessage) message; Console.WriteLine ("Receive:" + MSG.) Text); } catch (System.Exception e) {Console.WriteLine (e.message); } }
Start a consumer:
We found out that he started from 15, instead of starting from scratch like in the previous section and starting another consumer:
We found that the message was received from the start, and the previous message was lost.
The overall status is as follows:
We observe the management interface:
Generated a testing topics, and Subscribers have 2 subscriptions that are testing:
This only needs to be received in a timely manner where the message needs to be subscribed.
Source code Download
ACTIVEMQ Publish Subscription Mode