Reactor Netty TCP 服务器端-响应式编程-011

  ApiHug × {Postman|Swagger|Api...} = 快↑ 准√ 省↓

  1. GitHub - apihug/apihug.com: All abou the Apihug   
  2. apihug.com: 有爱,有温度,有质量,有信任
  3. ApiHug - API design Copilot - IntelliJ IDEs Plugin | Marketplace

   The Next Generation API Development Platform - ApiHug 

Reactor Netty提供了易于使用和配置的TcpServer 。它隐藏了创建TCP服务器所需的大部分Netty的功能,并增加了Reactive Streams背压。

一下例子镜像自 reactor netty 官方demo 在 gitee 镜像: TCP Server 例子open in new window

TCP(Transmission Control Protocol 传输控制协议)

特点:

  1. TCP是面向连接的服务,可靠的进程到进程通信的协议(重传机制)
  2. TCP报文段封装在IP数据包中
  3. IP首部 + TCP报文段(包含TCP包头,应用层数据)

Reactor Netty TCP 服务器端-响应式编程-011_第1张图片

#创建

public class Application {

  public static void main(String[] args) {
    DisposableServer server =
        TcpServer.create() // <1>
            .bindNow(); // <2>

    server.onDispose().block();
  }
}
  1. 创建一个TcpServer 实例用来做配置操作。
  2. 使用阻塞等待的方式启动服务器,直到初始化完成。

返回的 DisposableServer 提供了简单的服务器API,包括disposeNow() ,这个方法可以以阻塞等待的方式来关闭服务器。

#Host & Port

想要设置特定host和port,您可以用下面的方式来配置TCP服务器:

public class Application {

  public static void main(String[] args) {
    DisposableServer server =
        TcpServer.create()
            .host("localhost") // <1>
            .port(8080) // <2>
            .bindNow();

    server.onDispose().block();
  }
}
  1. 配置TCP服务器的host
  2. 配置TCP服务器的port

还可多端口服务:

public class MultiAddressApplication {

  public static void main(String[] args) {
    TcpServer tcpServer = TcpServer.create();
    DisposableServer server1 =
        tcpServer
            .host("localhost") // <1>
            .port(8080) // <2>
            .bindNow();

    DisposableServer server2 =
        tcpServer
            .host("0.0.0.0") // <3>
            .port(8081) // <4>
            .bindNow();

    Mono.when(server1.onDispose(), server2.onDispose()).block();
  }
}

你可能感兴趣的:(intellij-idea,spring,spring,boot,ApiHug)