1+ import java .io .IOException ;
12import com .rabbitmq .client .ConnectionFactory ;
23import com .rabbitmq .client .Connection ;
34import com .rabbitmq .client .Channel ;
45import com .rabbitmq .client .QueueingConsumer ;
56
67public class Worker {
8+
9+ private static final String TASK_QUEUE_NAME = "task_queue" ;
10+
711 public static void main (String [] argv )
812 throws java .io .IOException ,
913 java .lang .InterruptedException {
10- Connection connection = null ;
14+
1115 ConnectionFactory factory = new ConnectionFactory ();
1216 factory .setHost ("localhost" );
13- connection = factory .newConnection ();
17+ Connection connection = factory .newConnection ();
1418 Channel channel = connection .createChannel ();
1519
16- channel .queueDeclare ("task_queue" , true , false , false , null );
20+ channel .queueDeclare (TASK_QUEUE_NAME , true , false , false , null );
1721 System .out .println (" [*] Waiting for messages. To exit press CTRL+C" );
1822
1923 channel .basicQos (1 );
2024
2125 QueueingConsumer consumer = new QueueingConsumer (channel );
22- channel .basicConsume ("task_queue" , false , consumer );
26+ channel .basicConsume (TASK_QUEUE_NAME , false , consumer );
2327
2428 while (true ) {
2529 QueueingConsumer .Delivery delivery = consumer .nextDelivery ();
2630 String body = new String (delivery .getBody ());
27- System . out . println ( " [x] Received " + body );
28-
29- Thread . sleep ( charCount ( body , '.' ) * 1000 );
30- System .out .println (" [x] Done" );
31+
32+ System . out . println ( " [x] Received '" + body + "'" );
33+ doWork ( body );
34+ System .out .println (" [x] Done" );
3135
3236 channel .basicAck (delivery .getEnvelope ().getDeliveryTag (), false );
33- }
37+ }
3438 }
3539
36- private static int charCount (String body , char theChar ){
37- int count = 0 ;
38- for ( int index = 0 ; index < body . length (); index ++){
39- if ( theChar == body . charAt ( index )) count ++;
40+ private static void doWork (String task ) throws InterruptedException {
41+ for ( char ch : task . toCharArray ()) {
42+ if ( ch == '.' ) Thread . sleep ( 1000 );
43+ }
4044 }
41- return count ;
42- }
43- }
44-
45+ }
0 commit comments