在SpringBoot中整合使用Netty框架
Netty是一个非常优秀的Socket框架。如果需要在SpringBoot开发的app中,提供Socket服务,那么Netty是不错的选择。
Netty与SpringBoot的整合,我想无非就是要整合几个地方
- 让netty跟springboot生命周期保持一致,同生共死
- 让netty能用上ioc中的Bean
- 让netty能读取到全局的配置
整合Netty,提供WebSocket服务
这里演示一个案例,在SpringBoot中使用Netty提供一个Websocket服务。
servlet容器本身提供了websocket的实现,但这里用netty的实现 💖
添加依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
是的,不用声明版本号。因为 spring-boot-dependencies 中已经声明了最新的netty依赖。
通过yaml配置基本的属性
server:
port: 80
logging:
level:
root: DEBUG
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
shutdown:
enabled: true
netty:
websocket:
# Websocket服务端口
port: 1024
# 绑定的网卡
ip: 0.0.0.0
# 消息帧最大体积
max-frame-size: 10240
# URI路径
path: /channel
App使用了,actuator,并且开启暴露了 shutdown
端点,可以让SpringBoot App优雅的停机。
在这里通过 netty.websocket.*
配置 websocket服务相关的配置。
通过 ApplicationRunner 启动Websocket服务
import java.net.InetSocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;