需求介绍:
NATS是一个开源且高性能的消息系统,它常常被认为是”一个为云服务的中央神经系统”.它每秒钟可以传送百万条消息,所以非常适合用来连接微服务和IOT设备。
NATS是一个发布订阅方式的消息系统。在这类系统中,一个或多个消息发布者将特定的主题发送给一个消息中介者,然后消息中介者再将消息分发给任意客户端(或者这个主题的订阅者)。消息发布者不知道也不关心消息订阅者是谁,反之依然。由于我们可以在不影响系统其它部分的情况下增加新的消息发布者和订阅者,这样的架构使得系统的伸缩性变得很好并且可以比较容易地增加系统的容量。这种类型的系统非常适合用来监测服务器和终端设备;终端设备可以发送消息,我们可以订阅这些消息,然后通过邮件或者其他的方式发送消息通知。
下面我们会部署一个nats-server在windows上,然后使用java创建两个nats客户端,一个发送pub请求,一个发送sub请求,检查sub的这个客户端上能否收到信息。
服务端部署
2.下载windows版本,也可以用docker-image版,都很方便。
3.windows版本,下载之后,解压,双击gnatsd.exe即可运行
4.获得服务器地址:nats://localhost:4222
nats代码
1.先maven安装相关依赖,主要是nats的和json的,因为我们要pub一个json过去
Python
io.nats
jnats
2.2.0
com.google.code.gson
gson
2.8.5
1
2
3
4
5
6
7
8
9
10
11
io.nats
jnats
2.2.0
com.google.code.gson
gson
2.8.5
nats客户端(sub订阅)
Python
package nats.lzwtest;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import io.nats.client.Connection;
import io.nats.client.Dispatcher;
import io.nats.client.Nats;
public class SubscribeAsync {
public static void main(String[] args) {
try {
// [begin subscribe_async]
Connection nc = Nats.connect("nats://localhost:4222");
// Use a latch to wait for a message to arrive
CountDownLatch latch = new CountDownLatch(10);
// Create a dispatcher and inline message handler
Dispatcher d = nc.createDispatcher((msg) -> {
String str = new String(msg.getData(), StandardCharsets.UTF_8);
System.out.println(str);
latch.countDown();
});
// Subscribe
d.subscribe("lizhenwei");
// Wait for a message to come in
latch.await();
// Close the connection
nc.close();
// [end subscribe_async]
} catch (Exception e) {
e.printStackTrace();
}
}
}
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
packagenats.lzwtest;
importjava.nio.charset.StandardCharsets;
importjava.util.concurrent.CountDownLatch;
importio.nats.client.Connection;
importio.nats.client.Dispatcher;
importio.nats.client.Nats;
publicclassSubscribeAsync{
publicstaticvoidmain(String[]args){
try{
//[beginsubscribe_async]
Connectionnc=Nats.connect("nats://localhost:4222");
//Usealatchtowaitforamessagetoarrive
CountDownLatchlatch=newCountDownLatch(10);
//Createadispatcherandinlinemessagehandler
Dispatcherd=nc.createDispatcher((msg)->{
Stringstr=newString(msg.getData(),StandardCharsets.UTF_8);
System.out.println(str);
latch.countDown();
});
//Subscribe
d.subscribe("lizhenwei");
//Waitforamessagetocomein
latch.await();
//Closetheconnection
nc.close();
//[endsubscribe_async]
}catch(Exceptione){
e.printStackTrace();
}
}
}
nats客户端(pub发布)
Python
package nats.lzwtest;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.nats.client.Connection;
import io.nats.client.Nats;
// [begin publish_json]
class StockForJsonPub {
public String symbol;
public float price;
}
public class PublishJSON {
public static void main(String[] args) {
try {
Connection nc = Nats.connect("nats://localhost:4222");
// Create the data object
StockForJsonPub stk = new StockForJsonPub();
stk.symbol="GOOG";
stk.price=1200;
// use Gson to encode the object to JSON
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
String json = gson.toJson(stk);
// Publish the message
nc.publish("lizhenwei", json.getBytes(StandardCharsets.UTF_8));
// Make sure the message goes through before we close
nc.flush(Duration.ZERO);
nc.close();
System.out.println("pub success");
} catch (Exception e) {
e.printStackTrace();
}
}
}
// [end publish_json]
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
packagenats.lzwtest;
importjava.nio.charset.StandardCharsets;
importjava.time.Duration;
importcom.google.gson.Gson;
importcom.google.gson.GsonBuilder;
importio.nats.client.Connection;
importio.nats.client.Nats;
//[beginpublish_json]
classStockForJsonPub{
publicStringsymbol;
publicfloatprice;
}
publicclassPublishJSON{
publicstaticvoidmain(String[]args){
try{
Connectionnc=Nats.connect("nats://localhost:4222");
//Createthedataobject
StockForJsonPubstk=newStockForJsonPub();
stk.symbol="GOOG";
stk.price=1200;
//useGsontoencodetheobjecttoJSON
GsonBuilderbuilder=newGsonBuilder();
Gsongson=builder.create();
Stringjson=gson.toJson(stk);
//Publishthemessage
nc.publish("lizhenwei",json.getBytes(StandardCharsets.UTF_8));
//Makesurethemessagegoesthroughbeforeweclose
nc.flush(Duration.ZERO);
nc.close();
System.out.println("pub success");
}catch(Exceptione){
e.printStackTrace();
}
}
}
//[endpublish_json]
运行结果
sub端收到如下:
Python
{"symbol":"GOOG","price":1200.0}
1
{"symbol":"GOOG","price":1200.0}
联系作者,QQ: 357244849