Rabbit MQ Subscription method gets messages and can set persistence

Source: Internet
Author: User

Rabbit get the message by way: The subscription is actually registered to the queue consumer, through RPC to the queue server to send the registration consumer message, RabbitMQ server after receiving the message, This is a subscription message based on the content type of the message, which automatically sends the message through the socket (long connection) channel when the queue in MQ has a message.

can be done by

Set the RABBITMQ dispatch message, that is, to tell RABBITMQ each time only to the consumer processing a message, that is, waiting for the consumer to finish processing and has already processed the message to confirm, only send the next message, to prevent consumers too busy. As shown in the following:

Organize the code as follows:


Produce

public class Rabbitmqproduce {public static void main (string[] args) throws IOException, interruptedexception {Connection Factory Factory =new connectionfactory (); String routingkey= "Test"; String exchange= "Test";    Factory.sethost ("localhost");    Connection conn = Factory.newconnection ();    Channel channel =conn.createchannel ();        Send Message for    (int i=0;i<8000;i++) {    if (i%5==0) {    thread.sleep ($);    }    Byte[] Messagebodybytes = (i+ ""). GetBytes ();    If you set the queue to persistent, you also need to set the message to be persisted, messageproperties.persistent_text_plain    //That is, after setting the queue to persistent, You also need to set the messages that are sent to persist in order to ensure that queues and messages persist    //Consumers also make persistent claims at the time of declaration    Channel.basicpublish (Exchange, Routingkey, NULL, messagebodybytes);    System.out.println ("Send.." +i);    }    Channel.close ();      Conn.close ();}}


Customer

public class Rabbitmqcustomer {private static connectionfactory factory;private static String queryname= "test";p rivate Static Connection conn;private static Channel channel;private static string exchange= "test";p rivate static string routing key= "Test";p ublic static void Main (string[] args) throws Exception {start ();/** * Get the message by subscribing */Channel.basicconsu Me (QueryName, False, new Defaultconsumer (channel) {@Override public void handleshutdownsignal (String consume        Rtag, shutdownsignalexception Sig) {System.out.println ("= = =" +consumertag+ "=====" +sig.getmessage ());        Boolean isopenconnect = Conn!=null&&conn.isopen ();        Boolean Isopenchannel = Channel! = NULL && channel.isopen (); while (!isopenchannel| |! Isopenconnect) {try {System.out.println ("Connection failed reconnection ...."); start (); Thread.Sleep (3000);}          catch (Exception e) {e.printstacktrace ();} }} @Override public void Handledelivery (String cOnsumertag, Envelope Envelope, basicproperties Properties, byte[] body) throws IOException {//message sequence L        Ong Deliverytag = Envelope.getdeliverytag ();        string mes = new String (Body, "UTF-8");        System.out.println ("Received to message:" +mes);        Acknowledgement received, message receipt Channel.basicack (Deliverytag, true); }        });} public static void Start () throws IOException {factory = new connectionfactory (); Factory.sethost ("localhost"); Factory.setusername ("test"); Factory.setpassword ("test"); conn = Factory.newconnection (); channel = Conn.createchannel (); Channel.exchangedeclare (Exchange, "topic"); Channel.queuedeclare (QueryName, False, False, False, null);//declares Message Queuing, and is a persistent channel.queuebind (queryname, Exchange, Routingkey); Channel.basicqos (1); Message Distribution Processing}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Rabbit MQ Subscription method gets messages and can set persistence

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.