Reference: http://blog.csdn.net/lmj623565791/article/details/37620057
1. Production Task Task.java
Package cn.slimsmart.rabbitmq.demo.workqueue;
Import Com.rabbitmq.client.AMQP;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
Import Com.rabbitmq.client.ConnectionFactory;
Import com.rabbitmq.client.MessageProperties;
public class Task {//queue name private final static String queue_name = "workqueue-durable"; public static void Main (string[] args) throws Exception {//Create connection and channel ConnectionFactory factory = new Connectio
Nfactory ();
Factory.sethost ("192.168.101.174");
Specify User password Factory.setusername ("admin");
Factory.setpassword ("admin"); Specifies the port factory.setport (AMQP. PROTOCOL.
PORT);
Connection Connection = Factory.newconnection ();
Channel Channel = Connection.createchannel (); Boolean durable = true;
Set message persistence RABBITMQ does not allow the use of different parameters to redefine a queue, so already existing queues, we cannot modify their properties.
DECLARE Queues Channel.queuedeclare (queue_name, durable, false, false, NULL); OfSend 10 messages, followed by 1-10 points for (int i = 5; i > 0; i--) {String dots = "";
for (int j = 0; J <= i; j +) {dots = ".";
String message = "HelloWorld" + dots+dots.length (); Messageproperties.persistent_text_plain identifies our information as persistent channel.basicpublish ("", Queue_name, Messageproperties.
Persistent_text_plain, Message.getbytes ());
SYSTEM.OUT.PRINTLN ("Sent message: '" + Message + "");
//close channels and resources channel.close ();
Connection.close ();
}
}
2. Consumer work queues
Package cn.slimsmart.rabbitmq.demo.workqueue;
Import Com.rabbitmq.client.AMQP;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
Import Com.rabbitmq.client.ConnectionFactory;
Import Com.rabbitmq.client.QueueingConsumer;
public class Work {//queue name private final static String queue_name = "workqueue-durable";
public static void Main (string[] args) throws Exception {//differentiate output int hashcode = Work.class.hashCode () of different worker processes;
Create connection and channel ConnectionFactory factory = new ConnectionFactory ();
Factory.sethost ("192.168.101.174");
Specify User password Factory.setusername ("admin");
Factory.setpassword ("admin"); Specifies the port factory.setport (AMQP. PROTOCOL.
PORT);
Connection Connection = Factory.newconnection ();
Channel Channel = Connection.createchannel (); Boolean durable = true;
Set message persistence RABBITMQ does not allow the use of different parameters to redefine a queue, so already existing queues, we cannot modify their properties. declaring Queues Channel.quEuedeclare (queue_name, durable, false, false, NULL);
Queueingconsumer consumer = new Queueingconsumer (channel); /** * ack= True:round-robin forwarding consumer is killed, message will be lost * ack=false: Message reply, in order to ensure that the message will never be lost, RABBITMQ support Message ack
nowledgments).
* The consumer sends an answer to RABBITMQ, telling it that the information has been received and processed, and then RABBITMQ is free to delete the information.
* If a consumer is killed without sending a response, RABBITMQ will assume that the information is not fully processed and will then be retransmitted to another consumer.
* In this way, you can confirm that the information will not be lost, even if the consumer is occasionally killed.
* Consumers need to spend particularly long time is allowed. * */Boolean ACK = FALSE;
Open answer mechanism//Specify consumption queue Channel.basicconsume (queue_name, ACK, consumer);
Fair forwarding set the maximum number of service forwarding messages the next message is sent only when the consumer is free.
int prefetchcount = 1;
Channel.basicqos (Prefetchcount);
while (true) {Queueingconsumer.delivery Delivery = Consumer.nextdelivery ();
String message = new String (Delivery.getbody ()); System.out.printlN (hashcode + "Received message: '" + Message + "'");
DoWork (message);
System.out.println (hashcode + "Received done");
Send Answer Channel.basicack (Delivery.getenvelope (). Getdeliverytag (), false); }/** * each point takes 1s * @param task * @throws interruptedexception/private static void
DoWork (String Task) throws Interruptedexception {for (char Ch:task.toCharArray ()) {
if (ch = = '. ')
Thread.Sleep (1000);
}
}
}
Start several consumer work processes, use the producer to send messages, can observe the consumption situation.
To understand the routing mechanism of RABBITMQ, Exchange is a key. Exchange can be called a switch, and it seems to be called a router, which is used to select a route anyway. The core idea of RABBITMQ is that the publisher of the message does not send the message directly to the destination queue, in fact, it usually does not know which queue the message is sent to, it only knows to send message queues to Exchange. Exchange receives messages sent by the sender while the other side sends the message to the destination queue. Exchange must know which queues need to receive the message, whether it is added to a queue or to several queues, or simply thrown away.
If you use an empty string to declare an exchange, the system will use the "Amq.direct" exchange. We are using the Amq.direct type in front. Channel. Basicpublish ("", "Taskqueue", properties, bytes);
Direct Exchange sends a message to see Routingkey. For example, a direct Exchange name is defined as X1, and then a queue name is Q1 with ROUTINGKEY=K1 bound to Exchange X1, and when a Routekey message arrives at K2, then only X1 The news can reach the Q1.
Fanout-type exchange is better understood. It's a simple broadcast, and it ignores routingkey. So as long as there is a queue bound to fanout Exchange, messages sent through this exchange will be sent to those bound queue, regardless of whether you have entered the Routingkey.
The topic type of exchange gives us greater flexibility. By defining Routingkey can have selected subscriptions to some messages, Routingkey will be an expression. Exchange will decide whether to put the message in the corresponding queue by matching the routingkey of the binding. There are two expression symbols that allow us to choose: #和 *.
* (asterisk): represents any one word. Example: *.A will match A.A,B.A,C.A, etc.
# (well No.): 0 or more words with arbitrary code. Example: #.a will match A.A,AA.A,AAA.A, etc.
Topic Exchange sometimes behaves like other types of exchange, such as:
When Routingkey only has a #, its behavior is the same as that of fanout.
When Routingkey or something does not have an empty string, its behavior is the same as direct.
Note that the symbols represent words that are not characters. The definition of the words in an expression in RABBITMQ is separated by a. (dot).
Exchange using headers types is relatively small. I'll tell you later.
The following main use of code, to achieve direct, fanout, topic effect.