1、到官网下载nats-server-v2.2.0-linux-amd64.tar.gz 地址: https://nats.io/download/
2、解压至/home/nats-server-v2.2.0 目录,并在此目录新配置文件 simple.conf 内容如下
# Simple config file server_name: testing_server listen: 4222 http: 8222 # Enable TLS on reload #tls { # cert_file: "../test/configs/certs/server-cert.pem" # key_file: "../test/configs/certs/server-key.pem" # ca_file: "../test/configs/certs/ca.pem" # verify: true #} authorization { # users = [ # {user: alice, password: foo} # {user: bob, password: bar} # ] user: myUser password: myPassword timeout: 1 } # logging options debug: true trace: true logtime: true #syslog: true #remote_syslog: "udp://foo.com:33" # pid file pid_file: "/tmp/nats-server.pid" # prof_port #prof_port: 6543 # max_connections max_connections: 100 # max_subscriptions (per connection) max_subscriptions: 1000 # max_pending max_pending: 10000000 # maximum control line max_control_line: 2048 # maximum payload max_payload: 65536 # ping interval and no pong threshold ping_interval: "60s" ping_max: 3 # how long server can block on a socket write to a client write_deadline: "3s" lame_duck_duration: "4m" # report repeated failed route/gateway/leafNode connection # every 24hour (24*60*60) connect_error_reports: 86400 # report failed reconnect events every 5 attempts reconnect_error_reports: 5
3、启动服务
nohup /home/nats-server-v2.2.0/nats-server -c /home/nats-server-v2.2.0/simple.conf &
查看时候启动成功:
ps -ef|grep nats
4、JAVA客户端消息发布
package test.nats; import java.nio.charset.StandardCharsets; import io.nats.client.Connection; import io.nats.client.Nats; import io.nats.client.Options; /** * 发布消息 * @author 李小家 * */ public class Publish { public static void main(String[] args) throws Exception { Options o = new Options.Builder() .server("nats://47.107.**.***:4222") // .server("nats://servertwo:4222") .userInfo("myUser".toCharArray(), "myPassword".toCharArray()) .maxReconnects(-1).build(); Connection nc = Nats.connect(o); nc.publish("subject", "replyto", "hello world 测试内容!{"name":"张三"}".getBytes(StandardCharsets.UTF_8)); nc.close(); } }
5、JAVA客户端接收发布
package test.nats; import java.nio.charset.StandardCharsets; import io.nats.client.Connection; import io.nats.client.Dispatcher; import io.nats.client.Nats; import io.nats.client.Options; /** * 消息订阅 * @author 李小家 * */ public class Subscribe { public static void main(String[] args) throws Exception { Options o = new Options.Builder() .server("nats://47.107.**.***:4222") // .server("nats://servertwo:4222") .userInfo("myUser".toCharArray(), "myPassword".toCharArray()) .maxReconnects(-1).build(); Connection nc = Nats.connect(o); Dispatcher d = nc.createDispatcher((msg) -> { String response = new String(msg.getData(), StandardCharsets.UTF_8); System.out.println("response=="+response); }); d.subscribe("subject"); // nc.close(); } }
李小家
最新评论