Java for Web Learning Notes (94): Messages and Clusters (9) RABBITMQ and message mode (bottom) __java

Source: Internet
Author: User
Tags uuid rabbitmq
Example: implementation of RPC

This is an example of using RPC via AMQP, and RPC is a synchronous process that needs to wait for a response. In the actual application requires special messages, server may be slow performance, server may be shut down. Whether we must use RPC, or if we can replace it in an asynchronous way. Here, we are just demonstrating how to implement an RPC using the message management provided by RABBITMQ. The idea is as follows: RPC server receives messages from a queue rpc_queue, and RPC client sends request messages to the Rpc_queue queue. In the properties of the message, a UUID with this request is Correlation-id, which corresponds to the response. The properties of the message are reply-to with the client wishing to receive the response from that queue. RPC calls are synchronized by Blockingqueue to implement this process.

A small example will simply simulate the code for the Fibonacci function RPC server

public class Fibonaccirpcserver {private static final Logger log = Logmanager.getlogger ();

    private static final String Rpc_queue_name = "Rpc_queue";
    Private Connection Connection = null;

    Private Channel Channel = null; Public Fibonaccirpcserver () throws IOException, timeoutexception{connectionfactory factory = new Connectionfactor
        Y ();
        Factory.sethost ("191.8.1.107");
        Factory.setusername ("test");        
        Factory.setpassword ("123456");
        Connection = Factory.newconnection ();
    Channel = Connection.createchannel (); public void Open () throws IOException {Channel.queuedeclare (Rpc_queue_name, False, False, Fals
        e, NULL);
        Channel.basicqos (1);

        Log.info ("[x] awaiting RPC requests"); Consumer Consumer = new Defaultconsumer (channel) {@Override public void handledelivery (String con
 Sumertag, Envelope Envelope, basicproperties Properties, byte[] Body                   Throws IOException {try {basicproperties replyprops = new BASICPR Operties.
                    Builder (). Correlationid (Properties.getcorrelationid ()). build ();
                    String message = new String (Body, "UTF-8");
                    int n = integer.parseint (message); Log.info ("[.]
                    FIB ("+ Message +"));
                    String response = string.valueof (FIB (n));
                Channel.basicpublish ("", Properties.getreplyto (), Replyprops, Response.getbytes ("UTF-8"));
                finally {Channel.basicack (Envelope.getdeliverytag (), false);

        }

            }

        }; Channel.basicconsume (Rpc_queue_name, false, consumer); Required to answer} public void Close () {try {if (channel!= null) channel
        . Close (); catch (IOException | TimeoutException e) {e.printstacktrace ();
        } try{if (connection!= null) connection.close ();
        }catch (IOException e) {e.printstacktrace ();
        } private static int fib (int n) {if (n ==0) return 0;
        if (n = = 1) return 1;
    return fib (n-1) + fib (n-2); }
}
RPC Client Code
public class Fibonaccirpcclient {private static final Logger log = Logmanager.getlogger ();
    Private Connection Connection;
    Private Channel Channel;
    Private String Requestqueuename = "Rpc_queue";

    Private String Replyqueuename; Public Fibonaccirpcclient () throws IOException, timeoutexception{connectionfactory factory = new Connectionfactor
        Y ();
        Factory.sethost ("191.8.1.107");
        Factory.setusername ("test");
        Factory.setpassword ("123456");
        Connection = Factory.newconnection ();

        Channel = Connection.createchannel ();
    Replyqueuename = Channel.queuedeclare (). Getqueue ();
        public string Call (String message) throws Unsupportedencodingexception, IOException, interruptedexception{
        String Corrid = Uuid.randomuuid (). toString (); Basicproperties props = new Basicproperties.builder (). Correlationid (Corrid). ReplyTo (replyqueuename). Build
        (); Channel.basicpublish ("", RequestqueuenaMe, props, message.getbytes ("UTF-8"));

        Final blockingqueue<string> response = new arrayblockingqueue<string> (1); Channel.basicconsume (Replyqueuename, True, new Defaultconsumer (channel) {@Override public void ha Ndledelivery (String Consumertag, Envelope Envelope, basicproperties Properties, byte[] body) throws IO Exception {if (Properties.getcorrelationid (). Equals (Corrid)) {Response.offer (new Str
                ING (body, "UTF-8"));
        }
            }

        });
    return Response.take (); public void Close () {//... Slightly... Close channel and Connection}}

Above, we notice

Basicproperties props = new Basicproperties.builder (). Correlationid (Corrid). ReplyTo (Replyqueuename). build ();

Let's take a look at the grab bag:

RELATED links: My professional Java for WEB applications related articles

Related Article

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.