forked from rabbitinaction/sourcecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
104 lines (90 loc) · 2.55 KB
/
Client.java
File metadata and controls
104 lines (90 loc) · 2.55 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.AMQP.BasicProperties;
import org.json.JSONStringer;
import org.json.JSONException;
public class Client {
private Connection connection;
private Channel channel;
private String replyQueueName;
private QueueingConsumer consumer;
public Client init()
throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.111.192");
factory.setUsername("guest");
factory.setPassword("guest123");
connection = factory.newConnection();
channel = connection.createChannel();
return this;
}
public Client setupConsumer()
throws Exception {
replyQueueName = channel.queueDeclare().getQueue();
consumer = new QueueingConsumer(channel);
channel.basicConsume(replyQueueName, false, consumer);
return this;
}
public String call(String message) throws Exception {
String response = null;
channel.basicPublish(
"rpc",
"ping",
getRequestProperties(),
message.getBytes()
);
System.out.println("Sent 'ping' RPC call. Waiting for reply...");
while (true) {
Delivery delivery = consumer.nextDelivery();
response = new String(delivery.getBody(), "UTF-8");
break;
}
return response;
}
public void close() throws Exception {
connection.close();
}
private BasicProperties
getRequestProperties() {
return new BasicProperties
.Builder()
.replyTo(replyQueueName)
.build();
}
public static String createRequest()
throws JSONException {
float epoch = System.currentTimeMillis()/1000;
JSONStringer msg = new JSONStringer();
return msg
.object()
.key("client_name")
.value("RPC Client 1.0")
.key("time")
.value(Float.toString(epoch))
.endObject().toString();
}
public static void main(String[] args) {
Client client = null;
String response = null;
try {
client = new Client();
client.init().setupConsumer();
response = client.call(Client.createRequest());
System.out.println("RPC Reply --- " + response);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (client!= null) {
try {
client.close();
}
catch (Exception ignore) {}
}
}
}
}