RABBITMQ Study notes (not finished)

Source: Internet
Author: User
Tags ack rabbitmq
Connection

AMQP enables multiple MQ communication channel to be enabled on a TCP connection, and each channel can be applied as a traffic flow. Each AMQP program must have at least one connection and one channel.

        ConnectionFactory factory = new ConnectionFactory ();
        address[] Addrs = new address[] {new address ("192.168.1.10"), New Address ("192.168.1.11"), New  address (" 192.168.1.12 ")};
        Factory = new ConnectionFactory ();
        Factory.setusername ("admin");
        Factory.setpassword ("admin");
        Factory.setvirtualhost ("/myvhost");
        Factory.setconnectiontimeout (ten);

        try {
            Connection Connection =factory.newconnection (Addrs);
        } catch (IOException e) {
            //TODO Auto-generated Catch block
            e.printstacktrace ();
        }
        Channel channel = Connection.createchannel ();  

Each channel is assigned an integer identifier that is automatically maintained by the. CreateChannel () method of the connection () class. Alternatively, you can use. CreateChannel (x) to specify the channel ID, where x is the channel ID you want to use. In general, it is recommended to use the. CreateChannel () method to automatically assign channel identities to prevent collisions. Queue Declaration

Now we have a connection and channel that we can use. Now, our code will be divided into two applications, producers (producer) and consumers (consumer). We first create a consumer program that creates a queue called "Test_push" and a switch called "Sorting_room":

String queue = "Test_push";
Boolean durable = true;
Boolean exclusive = false;
Boolean autodelete = false;
map<java.lang.string,java.lang.object> arguments = null;
Channel.queuedeclare (queue, durable, exclusive, autodelete, arguments);

String exchange= "Sorting_room";
String type= "direct";
Boolean durable=true;
Boolean auto_delete=false;
map<java.lang.string,java.lang.object> arguments = null;
Channel.exchangedeclare (Exchange, type, durable,auto_delete, arguments);

This code first, it creates a queue called "Test_push", it is durable (re-established after reboot), and the last consumer will not automatically delete when disconnected (auto_delete=false). When creating a durable queue (or switch), it is important to set the Auto_delete to False, otherwise the queue will disappear when the last consumer disconnects, regardless of whether durable or not. If both durable and auto_delete are set to true, only queues with consumer activity can be automatically restored when the RABBITMQ crashes unexpectedly.

(You can notice another sign, called "Exclusive.") If set to True, only the consumer program that created the queue is allowed to connect to the queue. This queue is private to this consumer program).

There is another switch statement that creates a switch named "Sorting_room". The meaning of Auto_delete and durable is the same as the queue. However,. Exchangedeclare () also has another parameter called type, which specifies the type of switch to be created (as listed earlier): Fanout, direct, and topic. binding

So far, you've got a queue that can receive messages and a switch that can send messages. But we need to create a binding to connect them together.

String queue= "Test_push";
String exchange= "Sorting_room";
String routing_key= "Jason";
Channel.queuebind (queue, Exchange, Routing_key);

The process of this binding is very straightforward. Any message sent to the switch "Sorting_room" with the routing key "Jason" is routed to a queue named "Test_push". Receive Message calls

Now you have two ways to pull messages out of the queue.
The first is to call Chan.basic_get () and pull the next message out of the queue (if there is no message in the queue, Channel.basicget () returns none, so the code below Response.getbody () Will collapse when there is no news):

Boolean autoack = false;
GetResponse response = channel.basicget (queue, autoack);
String message = new String (Response.getbody (), "UTF-8");
SYSTEM.OUT.PRINTLN (message);
Boolean ack = true;
Channel.basicack (Response.getenvelope (). Getdeliverytag (), ACK);  

But what if you want the app to be notified immediately when the message arrives. In this case you cannot use Channel.basicget () and you need to register a new message with Chan.basic_consume () to arrive at the callback.

def recv_callback (msg):
    print ' Received: ' + msg.body
chan.basic_consume (queue= ' Po_box ', No_ack=true,
Callback=recv_callback, consumer_tag= "Testtag") while
True:
    chan.wait ()
chan.basic_cancel ("Testtag ")

Chan.wait () is placed inside an infinite loop, and the function waits on the queue until the next message arrives in the queue. Chan.basic_cancel () is used to unregister the callback function. The string specified in the parameter Consumer_tag and Chan.basic_consume () are registered all the time. In this example Chan.basic_cancel () will not be called, because it is an infinite loop ... But you need to know the call, so I put it in the code.

Another thing to be aware of is the No_ack parameter. This parameter can be passed to Chan.basic_get () and Chan.basic_consume (), which is false by default. When a message is removed from the queue, RABBITMQ needs to apply an explicit feedback that the message has been acquired. If no feedback is given over time, RABBITMQ will reassign the message to another consumer bound to the queue. Another situation is that the consumer disconnects, but the obtained message does not give back, and the RABBITMQ is equally redistributed. If the No_ack parameter is set to True, Py-amqplib adds a No_ack property to the next AMQP request, telling the AMQP server that it does not need to wait for feedback. However, most of the time, you may want to send your feedback manually, for example, by storing the message in the database before giving it back. Feedback is usually done by calling the Chan.basic_ack () method, using the message's Delivery_tag property as a parameter. See example code for Chan.basic_get (). Send Call

A producer. The following code example shows how to send a simple message to the swap area "Sorting_room" and mark it as the routing key "Jason":

msg = AMQP. Message ("Test message!")
msg.properties["Delivery_mode"] = 2
chan.basic_publish (msg,exchange= "Sorting_room", routing_key= "Jason")

You may have noticed that we set the Delivery_mode property of the message to 2 because both the queue and the switch are set to durable, and this setting guarantees that the message will persist, that is, it can be restored if the RABBITMQ is restarted before it is delivered to the consumer. Close

The last thing left (both producers and consumers need to call) is to close the channel and connect:

Chan.close ()
conn.close ()

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.