Rabbitmq/java Client Testing (complement: Leveraging threads)

Source: Internet
Author: User
Tags rabbitmq

A simple connection test was made last time. This is a little bit of a big addition. Use threads to combine producer consumer code into a single file.

I added the Recv.java (consumer) file to the Send.java (producer) in a thread.

The code is as follows:

 PackageMYRABBITMQ;Importcom.rabbitmq.client.ConnectionFactory;Importcom.rabbitmq.client.ConsumerCancelledException;ImportCom.rabbitmq.client.QueueingConsumer;Importcom.rabbitmq.client.ShutdownSignalException;Importcom.rabbitmq.client.Connection;Importjava.io.IOException;ImportJava.util.Scanner;ImportCom.rabbitmq.client.Channel;classRecvthreadextendsthread{recvthread (String name) {Super(name);//call the parent class with the constructor method of the parameter    }     Public voidrun () {FinalString queue_name = "Hello"; ConnectionFactory Factory=NewConnectionFactory (); Factory.sethost ("123.206.216.31"); Factory.setport (5672); Factory.setusername ("Admin"); Factory.setpassword ("Admin"); //open Connection and create channel, same as Send endConnection Connection =NULL; Try{Connection=factory.newconnection (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Channel Channel=NULL; Try{Channel=Connection.createchannel (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                                    //A queue is declared, primarily to prevent the message receiver from running this program before the queue does not exist when the queue is created.                     Try{channel.queuedeclare (queue_name,false,false,false,NULL); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                      //Create a queue consumerSystem.out.println ("[*] waiting for messages. To exit Press CTRL + C "); //Specify the consumption queue//Specify the consumption queueQueueingconsumer consumer =NewQueueingconsumer (channel); Try{channel.basicconsume (queue_name,true, consumer); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                       while(true) {queueingconsumer.delivery Delivery=NULL; Try{Delivery=Consumer.nextdelivery (); } Catch(shutdownsignalexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(consumercancelledexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } String Message=NewString (Delivery.getbody ()); System.out.println ("[x] Received '" + Message + "'"); }              }    } Public classSend {Private Final StaticString queue_name = "Hello";  Public Static voidMain (string[] args)throwsjava.io.IOException {/*** Create a connection to connect to MABBITMQ*/              //set the host IP or host name of the MABBITMQConnectionFactory Factory=NewConnectionFactory (); Factory.sethost ("123.206.216.31"); Factory.setport (5672); System.out.println ("Input your Username:"); Scanner un=NewScanner (system.in); String username=NULL; Username=Un.next (); System.out.println ("Input your password::"); Scanner up=NewScanner (system.in); String UserPassword=NULL; UserPassword=Up.nextline ();            Factory.setusername (username);            Factory.setpassword (UserPassword); //Create a connectionConnection Connection =factory.newconnection (); //Create a channelChannel Channel =Connection.createchannel (); //Specify a queueChannel.queuedeclare (Queue_name,false,false,false,NULL); //the message sentSYSTEM.OUT.PRINTLN ("Input What Wanna send:"); Scanner s=NewScanner (system.in); String message=NULL; Message=S.nextline (); //send a message to the queueChannel.basicpublish ("", Queue_name,NULL, Message.getbytes ()); System.out.println ("[x] Sent '" + Message + "'"); //turn off channels and connectionsChannel.close ();              Connection.close (); Recvthread Rthread=NewRecvthread ("Test1");        Rthread.start (); }  }

In addition, here is a comb for the typical concepts in RABBITMQ:

When you touch RABBITMQ, you may be confused by a bunch of concepts that are coming in, Exchange (exchanger), queue (queue), and Routing_key (routing), and what Connection (connections), Channel (pipeline). And in the case of the official website, some of the concepts will appear, some will not appear, and there is no particular clarity, so we must first understand the concept and process.

Now that we're using RABBITMQ to deal with the news, we need to know exactly what the message is.

(Example 1): From the perspective of the entity, we can regard the message as a cargo: we from a treasure, a certain east of the goods, the goods produced by the manufacturers, through the sellers, Courier sent to us, wherein: the goods is "news", manufacturers are producers (publisher), Buyers are consumers (consumer), a treasure and other platform is the Exchange (Exchange), logistics Express is the queue (queues).

(Example 2): From the virtual point of view, we can also think of the message as an order, this time, we are the order (message) producer, and the Merchant is the order of the consumer, and this time the queue is not express but run on the e-commerce platform (Exchange) information flow.

How many steps will it take to put the elephant in the freezer?
A: 3 steps, the first step to open the refrigerator door, the second step to put the elephant in the third step to close the refrigerator door.

So what steps do we need to make an order on the e-commerce platform?
First step: Turn on your computer
Step Two: Open the browser
Step three: Open an East website
Fourth Step: Select a product
Fifth Step: Select the Payment method (an east payment or a white bill to pay or a letter to pay)
Sixth step: Confirm payment
Seventh step: Close the browser
Eighth step: Turn off the computer

We compare the process of consumption with the life cycle of the message queue, and we will find a certain similarity
First step: Turn on the computer (connect to the specified RABBITMQ server, establish connection)
Step Two: Open the browser (get channel, ie open channel)
Step three: Open an East website (declaration exchanger, IE Exchange_declare)
Fourth Step: Select the product (Declaration queue, i.e. Queue_declare)
Fifth Step: Select the payment method (bind the queue and the switch, i.e. queue_bind).
Sixth step: Confirm Payment (consumer information, i.e. Basic_consume)
Seventh step: Close the browser (close the channel, that is, close channels)
Eighth step: Turn off the computer (close the connection, that is, close connection)

A complete message process should contain the above eight steps, but after you turn on your computer, there are a number of things you can choose from: You can open more than one browser (channel), or you can open many e-commerce websites (Exchange) in different browsers. Not to mention you can choose any item (queue) on your website, and choose your preferred payment method (Queue_bind). In other words, connection has only one, but channel, Exchange, Exchange_type, queue, Routing_key can be organized according to certain rules and requirements.

Concept part reprinted from: http://m.blog.csdn.net/article/details?id=51039938

Rabbitmq/java Client Testing (complement: Leveraging threads)

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.