forked from rabbitmq/rabbitmq-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPCClient.java
74 lines (56 loc) · 2.28 KB
/
RPCClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.IOException;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.AMQP.BasicProperties;
import java.util.UUID;
public class RPCClient {
private static final String RPC_QUEUE_NAME = "rpc_queue";
static class FibonacciClient {
private Channel channel;
private String queue;
public FibonacciClient(Channel chann, String queueName){
channel = chann;
queue = queueName;
}
public String call(String message)
throws java.io.IOException,
java.lang.InterruptedException {
String replyQueueName = channel.queueDeclare().getQueue();
String corrId = UUID.randomUUID().toString();
BasicProperties props = new BasicProperties();
props.setReplyTo(replyQueueName);
props.setCorrelationId(corrId);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(replyQueueName, true, consumer);
channel.basicPublish("", queue, props, message.getBytes());
String response = "";
while (!validResponse(response)){
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
response = new String(delivery.getBody());
}
return response;
}
private Boolean validResponse(String response){
return (response.length() > 0);
}
}
private static Connection defaultConnection()throws java.io.IOException{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
return factory.newConnection();
}
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
Connection connection = defaultConnection();
Channel channel = connection.createChannel();
RPCClient.FibonacciClient rpc = new RPCClient.FibonacciClient(channel, RPC_QUEUE_NAME);
System.out.println(" [x] Requesting fib(30)");
String response = rpc.call("30");
System.out.println(" [.] Got '" + response + "'");
channel.close();
connection.close();
}
}