@@ -7,36 +7,51 @@ public class ReceiveLogsTopic {
77
88 private static final String EXCHANGE_NAME = "topic_logs" ;
99
10- public static void main (String [] argv ) throws Exception {
11-
12- ConnectionFactory factory = new ConnectionFactory ();
13- factory .setHost ("localhost" );
14- Connection connection = factory .newConnection ();
15- Channel channel = connection .createChannel ();
16-
17- channel .exchangeDeclare (EXCHANGE_NAME , "topic" );
18- String queueName = channel .queueDeclare ().getQueue ();
10+ public static void main (String [] argv ) {
11+ Connection connection = null ;
12+ Channel channel = null ;
13+ try {
14+ ConnectionFactory factory = new ConnectionFactory ();
15+ factory .setHost ("localhost" );
16+
17+ connection = factory .newConnection ();
18+ channel = connection .createChannel ();
19+
20+ channel .exchangeDeclare (EXCHANGE_NAME , "topic" );
21+ String queueName = channel .queueDeclare ().getQueue ();
1922
20- if (argv .length < 1 ){
21- System .err .println ("Usage: ReceiveLogsTopic [binding_key]..." );
22- System .exit (1 );
23- }
23+ if (argv .length < 1 ){
24+ System .err .println ("Usage: ReceiveLogsTopic [binding_key]..." );
25+ System .exit (1 );
26+ }
2427
25- for (String bindingKey : argv ){
26- channel .queueBind (queueName , EXCHANGE_NAME , bindingKey );
27- }
28+ for (String bindingKey : argv ){
29+ channel .queueBind (queueName , EXCHANGE_NAME , bindingKey );
30+ }
2831
29- System .out .println (" [*] Waiting for messages. To exit press CTRL+C" );
32+ System .out .println (" [*] Waiting for messages. To exit press CTRL+C" );
3033
31- QueueingConsumer consumer = new QueueingConsumer (channel );
32- channel .basicConsume (queueName , true , consumer );
34+ QueueingConsumer consumer = new QueueingConsumer (channel );
35+ channel .basicConsume (queueName , true , consumer );
3336
34- while (true ) {
35- QueueingConsumer .Delivery delivery = consumer .nextDelivery ();
36- String message = new String (delivery .getBody ());
37- String routingKey = delivery .getEnvelope ().getRoutingKey ();
37+ while (true ) {
38+ QueueingConsumer .Delivery delivery = consumer .nextDelivery ();
39+ String message = new String (delivery .getBody ());
40+ String routingKey = delivery .getEnvelope ().getRoutingKey ();
3841
39- System .out .println (" [x] Received '" + routingKey + "':'" + message + "'" );
42+ System .out .println (" [x] Received '" + routingKey + "':'" + message + "'" );
43+ }
44+ }
45+ catch (Exception e ) {
46+ e .printStackTrace ();
47+ }
48+ finally {
49+ if (connection != null ) {
50+ try {
51+ connection .close ();
52+ }
53+ catch (Exception ignore ) {}
54+ }
4055 }
4156 }
4257}
0 commit comments