The last blog post briefly introduced the basics of RABBITMQ and wrote a classic language starter program--helloworld. In this blog post we will create a Task Force column to distribute time-consuming tasks among workers (consumer). It is also an example of a translated website. Task Force Column
In the previous blog post, we completed a simple send and receive message program for the declared queue. Below we will create a work queue to distribute time-consuming tasks to multiple workers (consumer).
The primary task of the Work queue (aka: Task queue) is to avoid immediately doing a resource-intensive task that must wait for completion. Instead, we do task scheduling: encapsulate the task as a message and send it to the queue. The worker running in the background (consumer) takes it out and executes it eventually. When you run multiple workers (consumer), the tasks in the queue are worked on for shared execution.
Such a concept is useful for Web applications that handle complex tasks in a request window for an HTTP short link.
prepare to use the Thread.Sleep () method to simulate time-consuming. Use the number of decimal points to represent the complexity of the task. Each point will live in a 1s "work". For example, Hello ... It takes 3s of time to finish processing.
Send side (producer): Newtask.java
[java] View Plain copy public class newtask { private final static string queue_name = "Hello"; public static void main (String[] args) throws ioexception { /** * Create a connection to connect to mabbitmq */ connectionfactory factory = new connectionfactory (); // Set MABBITMQ host IP or host name factory.sethost ("127.0.0.1"); // Create a connection connectiOn connection = factory.newconnection (); // Create a channel channel channel = connection.createchannel (); // Specify a queue channel.queuedeclare (queue_name, false, False, false, null); // messages sent String message = "Hello world ..."; // send a message to the queue channel.basicpublish ("", queue_name, null, message.getbytes ()); system.out.println (" [x] Sent ") + message + "'"); // close channels and connections channel.close (); connection.close (); } }
Worker (consumer) Worker.java
[Java] View plain copy public class Worker {private final static String queue_name = "Hello"; public static void Main (string[] argv) throws IOException, interruptedexception {connectionfactory factory =