NATS发布与监听

NATS

NATS的作用不多讲,直接实例。

新建项目

新建项目时选择Maven,可以选择右侧的quickstart,快速新建一个maven项目。
在这里插入图片描述

项目一

在test项目中,首先加入nats的依赖。
然后根据nats文档,写publish功能。

// maven  pom.xml中
<dependency>
      <groupId>io.nats</groupId>
      <artifactId>jnats</artifactId>
      <version>2.2.0</version>
    </dependency>
// main函数中
public class App {
    public static void main(String[] args) throws IOException, InterruptedException {
        Connection nc = Nats.connect("nats://127.0.0.1:4222");
        for(int i=0; i<=30; i++){
            nc.publish("subject", ("hello world" + i).getBytes(StandardCharsets.UTF_8));
        }


        System.out.println("Hello World!");
    }
}

项目二

在test2项目中,首先加入nats的依赖。
然后根据nats文档,写listen功能。

// maven  pom.xml中
<dependency>
      <groupId>io.nats</groupId>
      <artifactId>jnats</artifactId>
      <version>2.2.0</version>
    </dependency>
// main函数中  收到消息即退出
public class App {
    public static void main(String[] args) throws IOException, InterruptedException {
        Connection nc = Nats.connect("nats://127.0.0.1:4222");
        Subscription sub = nc.subscribe("subject");
        Message msg = sub.nextMessage(Duration.ofMinutes(20));

        String response = new String(msg.getData(), StandardCharsets.UTF_8);
        System.out.println(response);
    }
}
// main函数中  持续监听
public class App {
   public static void main(String[] args) throws IOException, InterruptedException {
        Connection nc = Nats.connect("nats://127.0.0.1:4222");
        Dispatcher d = nc.createDispatcher((msg) -> {
            String response = new String(msg.getData(), StandardCharsets.UTF_8);
            System.out.println(response);
        });

        d.subscribe("subject");
    }
}

参考网址

java-nats: https://github.com/nats-io/java-nats

nats官网: https://nats.io/download/nats-io/jnats/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值