/src/test/java/com/rabbitmq/messagepatterns/unicast/UnicastClient.java
Java | 105 lines | 88 code | 11 blank | 6 comment | 11 complexity | 25fa2f9f868d5ec0a9d677e02522a899 MD5 | raw file
1package com.rabbitmq.messagepatterns.unicast; 2 3import com.rabbitmq.client.ConnectionFactory; 4import com.rabbitmq.client.Channel; 5import com.rabbitmq.client.Connection; 6 7import java.util.HashSet; 8import java.util.Set; 9import java.io.IOException; 10 11public class UnicastClient { 12 13 public static void main(String[] args) throws Exception { 14 UnicastClient c = new UnicastClient(); 15 c.run(args[0], args[1], Integer.parseInt(args[2])); 16 } 17 18 Set pending = new HashSet(); 19 20 int sent; //requests sent 21 int recv; //requests received 22 int pend; //pending requests 23 int disc; //replies discarded 24 25 UnicastClient() { 26 } 27 28 MessageSentListener listener = new MessageSentListener() { 29 public void messageSent(Message msg) { 30 if (msg.getCorrelationId() == null) { 31 sent++; 32 pend++; 33 } 34 displayStats(); 35 } 36 }; 37 38 void displayStats() { 39 System.out.printf("\r" + 40 "sent %d, " + 41 "recv %d, " + 42 "pend %d, " + 43 "disc %d", 44 sent, recv, pend, disc); 45 } 46 47 void run(final String me, final String you, int sleep) throws Exception { 48 Connector conn = 49 Factory.createConnector(new ConnectionBuilder() { 50 public Connection createConnection() throws IOException { 51 return new ConnectionFactory().newConnection(); 52 } 53 }); 54 Messaging m = Factory.createMessaging(); 55 m.setConnector(conn); 56 m.setIdentity(me); 57 m.addMessageSentListener(listener); 58 m.addSenderSetupListener(new ChannelSetupListener() { 59 public void channelSetup(Channel channel) throws IOException { 60 //We declare the recipient queue here to avoid 61 //sending messages into the ether. That's an ok 62 //thing to do for testing 63 channel.queueDeclare(you, true, false, false, null); //durable 64 } 65 }); 66 m.addReceiverSetupListener(new ChannelSetupListener() { 67 public void channelSetup(Channel channel) throws IOException { 68 channel.queueDeclare(me, true, false, false, null); //durable 69 } 70 }); 71 m.init(); 72 byte[] body = new byte[0]; 73 for (int i = 0; ; i++) { 74 //send 75 Message msg = m.createMessage(); 76 msg.setBody(body); 77 msg.setTo(you); 78 msg.getProperties().setDeliveryMode(2); 79 m.send(msg); 80 pending.add(msg.getMessageId()); 81 //handle inbound 82 while (true) { 83 ReceivedMessage r = m.receiveNoWait(); 84 if (r == null) break; 85 if (r.getCorrelationId() == null) { 86 recv++; 87 displayStats(); 88 m.send(m.createReply(r)); 89 } else { 90 if (pending.contains(r.getCorrelationId())) { 91 pending.remove(r.getCorrelationId()); 92 pend--; 93 } else { 94 disc++; 95 } 96 displayStats(); 97 } 98 m.ack(r); 99 } 100 //Slow down to prevent pending from growing w/o bounds 101 Thread.sleep(sleep + pend); 102 } 103 } 104} 105