java连接stk外部接口_java使用nats-client进行pub/sub发送json的实例

需求介绍:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值