The client simply has to send a message to the server, and just sits there waiting for the answer. The variation is that I wrote such a powerful client that could even kill the server. To do that it just has to send an empty message. This is not a very safe behavior, but it is handy to show how to manage uncommon messages, at least in the RPC by messaging pattern, where the client doesn't wait for an answer.
Here is the most interesting part of the client code, you could also have a look to the source code for the complete Java class, that contains both server and client functionality:
// ... if(arg.equalsIgnoreCase("x")) { System.out.println("Terminating Fibonacci server"); channel.basicPublish("", RPC_QUEUE_NAME, null, null); // 1 } else { String queueName = channel.queueDeclare().getQueue(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); // 2 String id = UUID.randomUUID().toString(); // 3 BasicProperties props = new BasicProperties.Builder().correlationId(id).replyTo(queueName).build(); // 4 channel.basicPublish("", RPC_QUEUE_NAME, props, arg.getBytes()); // 5 System.out.println("Reply to " + queueName + ", " + id); System.out.print("fibonacci(" + arg + ") = "); while (true) { // 6 QueueingConsumer.Delivery delivery = consumer.nextDelivery(); if (delivery.getProperties().getCorrelationId().equals(id)) { // 7 System.out.println(new String(delivery.getBody())); // 8 break; } } } // ...1. This is the killer empty message for the RPC Fibonacci server.
2. An implicit acknowledgment is enough in this case.
3. As explained talking about the server, a unique correlation id is used to ensure the matching between request and reply. Here we generate it using the UUID facility.
4. The correlation id and the name for the specific queue created exclusively for this client is passed to the server in the properties associated to the message.
5. Message and properties are sent.
6. We loop indefinitely, discarding all the messages that are not relevant.
7. That's it! The correlation id matches.
8. In the message body we find the reply to our question, and we can terminate.
No comments:
Post a Comment