-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubscribe2.java
More file actions
54 lines (45 loc) · 1.78 KB
/
Copy pathSubscribe2.java
File metadata and controls
54 lines (45 loc) · 1.78 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
package nats;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import io.nats.client.Connection;
import io.nats.client.Dispatcher;
import io.nats.client.Message;
import io.nats.client.Nats;
import io.nats.client.Subscription;
public class Subscribe2 {
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException, TimeoutException {
Connection nc = Nats.connect("nats://user:123123@10.0.0.132:4222");
Map<String, Consumer<Message>> handlers = new HashMap<>(32);
handlers.put("subject", Subscribe2::doSomething1);
handlers.put("subject2", Subscribe2::doSomething2);
handlers.put("subject3", Subscribe2::doSomething3);
Dispatcher disp = nc.createDispatcher((msg) -> {
Consumer<Message> handler = handlers.get(msg.getSubject());
if (handler != null) {
handler.accept(msg);
}
});
handlers.keySet().forEach(disp::subscribe);
}
public static void doSomething1(Message msg) {
System.out.println("doSomething1 ======== ");
String response = new String(msg.getData(), StandardCharsets.UTF_8);
System.out.println(response);
}
public static void doSomething2(Message msg) {
System.out.println("doSomething2 ======== ");
String response = new String(msg.getData(), StandardCharsets.UTF_8);
System.out.println(response);
}
public static void doSomething3(Message msg) {
System.out.println("doSomething3 ======== ");
String response = new String(msg.getData(), StandardCharsets.UTF_8);
System.out.println(response);
}
}