SpringBoot-Webflux-Netty(四)
SpringBoot Netty 配置
配置启动端口
@Component
public class NettyWebServerFactoryPortCustomizer
implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {
@Override
public void customize(NettyReactiveWebServerFactory serverFactory) {
serverFactory.setPort(8089);
}
}
配置 EventLoopGroup
EventLoopNettyCustomizer 配置类
public class EventLoopNettyCustomizer implements NettyServerCustomizer {
@Override
public HttpServer apply(HttpServer httpServer) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup();
return httpServer.tcpConfiguration(tcpServer -> tcpServer
.bootstrap(serverBootstrap -> serverBootstrap
.group(bossGroup, workGroup)
.handler(new LoggingHandler(LogLevel.DEBUG))
.option(ChannelOption.SO_BACKLOG, 128)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.channel(NioServerSocketChannel.class)));
}
}
NettyReactiveWebServerFactory 工厂类
@Bean
public NettyReactiveWebServerFactory nettyReactiveWebServerFactory() {
NettyReactiveWebServerFactory webServerFactory = new NettyReactiveWebServerFactory();
// 同时可以扩展 SSL
webServerFactory.addServerCustomizers(new EventLoopNettyCustomizer());
return webServerFactory;
}
查看日志
要启用Netty访问日志记录,实用配置参数-Dreactor.netty.http.server.accessLogEnabled = true
。
新建两个 SpringBoot 项目
使用 Flux 写法
@GetMapping("flux")
public Mono<String> reactor() {
return Mono.just("hello world");
}
使用 Mvc 写法
@GetMapping("mvc")
public String hello() {
return "hello world";
}