RABBITMQ Example Tutorial: Publish/Subscriber Message Queuing

Source: Internet
Author: User
Tags rabbitmq

  Messaging Switches (Exchange)


The core idea of the RABBITMQ message model is that producers never send any messages directly to the queue, and in general, producers don't even know which queues the messages should be sent to.


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/74/54/wKiom1YZeRCgrXh9AAA8_sKBnCU136.jpg "title=" Publish-subscriber-01.png "alt=" Wkiom1yzercgrxh9aaa8_skbncu136.jpg "/>

Instead, producers can only send messages to the switch (Exchange). The switch functions very simply by receiving messages from the producer and pushing messages to the queue on the other side. The switch must know clearly how the message handles every message it receives. Should I append to a specified queue? Should I append to more than one queue? Or should they be discarded? These rules are defined by the type of switch.


The types of switches are: Direct,topic,headers and fanout. Let's take fanout as an example to create a "logs" type of switch.


Channel.exchangedeclare ("Logs", "fanout");


The fanout switch is very simple, and it broadcasts all the messages it receives for all queues.


Switch naming


In the previous example, we did not understand any concept of the switch and could also send a message because we used the default switch (""), but we could use our custom switch later.


Channel.basicpublish ("", "Hello", NULL, Message.getbytes ()); Empty string switch Channel.basicpublish ("Logs", "", NULL, Message.getbytes ()); Logs switch


  Temporary queue (temporary Queues)


In the previous example, we specified a specific name (such as Hello and task_queue) for the queue, and it was important to name the queue because the producer and the consumer were the queue names to deliver the message.


But for the log message queue, we listen to all the log messages, not some of the subsets. And we're only focusing on what's happening now, not on historical news, but we need to do this to solve these problems:


First, when we connect the rabbit server, we need a new empty queue. We can randomly generate a queue name or let the server randomly generate a queue name.


Second, the queue should be automatically deleted when the message consumer loses connectivity.


In Java, we use the Queuedeclare () method without parameters to create a non-persisted, unique queue that is automatically deleted after use.


String queuename = Channel.queuedeclare (). Getqueue ();


QueueName may be a random queue name such as AMQ.GEN-JZTY20BRGKO-HJMUJJ0WLG.


Message binding (Bindings)


Earlier we created a fanout type of switch and queue. Now you need to tell the switch to send messages to the queue. The relationship between the switch and the queue is the message binding (binding).


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/74/51/wKioL1YZemfT9Am4AAA7uKydZt4912.jpg "title=" Publish-subscriber-02.png "alt=" Wkiol1yzemft9am4aaa7ukydzt4912.jpg "/>

Use the following code logs the switch will pass the message to the queue.


Channel.queuebind (QueueName, "Logs", "" ");


Put the switch and message bindings together


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/74/54/wKiom1YZetLSZ2z_AABbZcUcUF0159.jpg "title=" Publish-subscriber-03.png "alt=" Wkiom1yzetlsz2z_aabbzcucuf0159.jpg "/>


Now we have a message producer that commits the log, it's not much different from our previous message sender, and the only difference is that we send the message to the logs switch instead of the switch without the name. When sending a message, we need to provide a route, although it does not work in the fanout switch. Here is the Java code to commit the log.


  Emitlog.java

package com.favccxx.favrabbit;import com.rabbitmq.client.channel;import  com.rabbitmq.client.connection;import com.rabbitmq.client.connectionfactory;public class  emitlog { private static final string exchange_name =  "Logs";  Public static void main (STRING[]&NBSP;ARGV)  throws Exception {   Connectionfactory factory = new connectionfactory ();   factory.sethost ("localhost ");   connection connection = factory.newconnection ();   channel channel  = connection.createchannel ();   channel.exchangedeclare (exchange_name,  "fanout");   string[] sendmsgs = {"I",  "Saw",  "a",  "dog"};  string  message = getmessage (SENDMSGS);   channel.basicpublish (EXCHANGE_NAME,  "",  Null, message.getbytes ("UTF-8")); &NBSP;&NBSP;SYSTEM.OUt.println (" [x] Sent " " + message + " ");   channel.close ();   connection.close ();  } private static string getmessage (String[]  strings)  {  if  (strings.length < 1)    return  "info:  Hello world! ";   return joinstrings (strings,  " "); } private static string  Joinstrings (String[] strings, string delimiter)  {  int length =  strings.length;  if  (length == 0)    return  "";   Stringbuilder words = new stringbuilder (Strings[0]);  for  (int i  = 1; i < length; i++)  {   words.append (delimiter). Append ( Strings[i]);   }  return words.tostring ();  }}



As shown above, after establishing a connection to the messaging server, a switch is declared because the system does not allow publishing to the empty switch. If no queue is bound to the switch, the message is lost, but we don't have to worry about it. If no consumer listens to the message, we discard the message.


  Receive Message Code Receivelogs.java


Package com.favccxx.favrabbit;import java.io.ioexception;import com.rabbitmq.client.amqp;import  com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import  com.rabbitmq.client.connectionfactory;import com.rabbitmq.client.consumer;import  com.rabbitmq.client.defaultconsumer;import com.rabbitmq.client.envelope;public class  receivelogs { private static final string exchange_name =  "Logs";  public static void main (STRING[]&NBSP;ARGV)  throws Exception {   Connectionfactory factory = new connectionfactory ();   factory.sethost ("localhost ");   connection connection = factory.newconnection ();   channel channel  = connection.createchannel ();   channel.exchangedeclare (exchange_name,  "fanout");   string queuename = channel.queuedeclare ().Getqueue ();   channel.queuebind (queuename, exchange_name,  "");   System.out.println (" [*] waiting for messages. to exit press ctrl+c");   consumer consumer = new defaultconsumer (channel)  {   @ Override   public void handledelivery (string consumertag, envelope  Envelope, amqp. Basicproperties properties,     byte[] body)  throws IOException  {    string message = new string (body,  "UTF-8");     system.out.println (" [x] Received " " + message + " ");    }  };  channel.basicconsume (Queuename, true, consumer);  } }



  Test data


Run several instance of the log message receiver, send a message using the log message sender, and discover that each log message recipient receives the same data indicating that the publish subscription was successful.


[x] Received ' I saw a dog '




This article is from the "This person's IT World" blog, be sure to keep this source http://favccxx.blog.51cto.com/2890523/1701738

RABBITMQ Example Tutorial: Publish/Subscriber Message Queuing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.