Connection
AMQP enables multiple MQ traffic channel on a single 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"), the new address ("192.168.1.11"), the 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, which 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 identity you want to use. In general, the. CreateChannel () method is recommended to automatically assign channel identities to prevent conflicts. Queue Declaration
Now we have a connection and a 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, and he 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);
First of all, it creates a queue called "Test_push", which is durable (recreated after reboot) and is not automatically deleted when the last consumer disconnects (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 durable. If both durable and auto_delete are set to true, only queues with consumer activity can automatically recover when the RABBITMQ crashes unexpectedly.
(You can notice another sign called "exclusive".) If set to True, only the consumer program that created the queue will be allowed to connect to the queue. This queue is private to this consumer program.
There is also another switch declaration that creates a switch named "Sorting_room". The meaning of Auto_delete and durable is the same as that of queues. However,. Exchangedeclare () also has another parameter called type, which specifies the type of switch to create (as listed earlier): Fanout, direct, and topic. binding
So far, you've got a queue to receive messages and a switch to send messages to. But we need to create a binding to connect them.
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 get messages out of the queue.
The first is to invoke Chan.basic_get () to pull the next message out of the queue (if there is no message in the queue, Channel.basicget () returns none, so the following code 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 application to be notified immediately when the message arrives? In this case you cannot use Channel.basicget (), you need to register a callback with Chan.basic_consume () to arrive at a new message.
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 in an infinite loop, and the function waits on the queue until the next message arrives at the queue. Chan.basic_cancel () is used to unregister the callback function. Parameter consumer_tag the specified string and Chan.basic_consume () are registered all the time. In this example Chan.basic_cancel () is not invoked because it is an infinite loop ... But you need to know this call, so I put it in the code.
Another thing to note is the No_ack parameter. This parameter can be passed to Chan.basic_get () and Chan.basic_consume () and the default is False. When a message is fetched from the queue, RABBITMQ needs to apply an explicit feedback that the message has been obtained. If no feedback is given over a period of time, RABBITMQ will reassign the message to another consumer bound to the queue. Another scenario is when the consumer disconnects, but the message gets no feedback, and the RABBITMQ is also reassigned. If the No_ack parameter is set to True, Py-amqplib adds a no_ack attribute to the next AMQP request, telling the AMQP that the server does not need to wait for feedback. But most of the time, you may want to send your own feedback manually, for example, by saving the message to a database before giving it back. Feedback is usually done using the Delivery_tag property of the message as a parameter by calling the Chan.basic_ack () method. See the instance 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 the queues and switches are set to durable, and this setting guarantees that the message will be persisted, that is, it can be restored if RABBITMQ reboots before it is delivered to the consumer. off
The last thing left (both producers and consumers need to call) is to turn off channel and connections:
Chan.close ()
conn.close ()