|
| 1 | +import com.rabbitmq.client.ConnectionFactory; |
| 2 | +import com.rabbitmq.client.Connection; |
| 3 | +import com.rabbitmq.client.Channel; |
| 4 | +import com.rabbitmq.client.QueueingConsumer; |
| 5 | + |
| 6 | +public class Worker { |
| 7 | + public static void main(String[] argv) |
| 8 | + throws java.io.IOException, |
| 9 | + java.lang.InterruptedException { |
| 10 | + Connection conn = null; |
| 11 | + ConnectionFactory factory = new ConnectionFactory(); |
| 12 | + factory.setHost("localhost"); |
| 13 | + conn = factory.newConnection(); |
| 14 | + Channel chan = conn.createChannel(); |
| 15 | + |
| 16 | + // make durable |
| 17 | + chan.queueDeclare("task_queue", true, false, false, null); |
| 18 | + System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); |
| 19 | + |
| 20 | + // prefetch 1 |
| 21 | + chan.basicQos(1); |
| 22 | + QueueingConsumer consumer = new QueueingConsumer(chan); |
| 23 | + chan.basicConsume("task_queue", false, consumer); |
| 24 | + |
| 25 | + while (true) { |
| 26 | + QueueingConsumer.Delivery delivery = consumer.nextDelivery(); |
| 27 | + String body = new String(delivery.getBody()); |
| 28 | + System.out.println(" [x] Received " + body); |
| 29 | + Thread.sleep(doDots(body)); // simulate action |
| 30 | + System.out.println(" [x] Done"); |
| 31 | + // acknowledge |
| 32 | + chan.basicAck(delivery.getEnvelope().getDeliveryTag(), false); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + |
| 37 | + private static int doDots(String body){ |
| 38 | +// just do something to get a number for simulation |
| 39 | + int x = body.indexOf('.') ; |
| 40 | + if (x < 0) return 0; |
| 41 | + body = body.substring(x); |
| 42 | + return body.length() ; |
| 43 | + } |
| 44 | +} |
0 commit comments