简单描述SpringBoot与Netty的初步集成,没有太深入的研究,搭建TCP/IP通信
依赖包导入
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
端口配置
在application.yml中配置:
server:
netty:
connection-timeout: 10
netty-port: 8888
Netty的端口通过@Value()注入
初始化通道
继承ChannelInitializer类,重写initChannel方法
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import java.nio.charset.Charset;
/**
* 通道初始化
*/
public class BootNettyChannelInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) throws Exception {
//设置一次接收一整行数据的,且大小为1024(可以不设置),需放在最前边
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
//添加心跳检测(目前是设置15s读检测)
ch.pipeline().addLast(new IdleStateHandler(15, 0, 0));
//设置编码格式(项目暂时接收的是GB2312格式)
ch.pipeline().addLast("decoder", new StringDecoder(Charset.forName("GB2312")));
ch.pipeline().addLast("encoder", new StringEncoder(Charset.forName("GB2312")));
//自定义ChannelInboundHandlerAdapter(放在最后)
ch.pipeline().addLast(new BootNettyChannelInboundHandlerAdapter());
}
}
如编写I/O读写处理类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.idcsol.edc.netty.common.NettySocketHolder;
import com.idcsol.edc.netty.common.SpringUtil;
import com.idcsol.edc.service.nettyService.NettyService;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* I/O数据读写处理类
*
*/
@Slf4j
public class BootNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter{
/**
* 从客户端收到新的数据时,这个方法会在收到消息时被调用
*
* @param ctx
* @param msg
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("channelRead:read msg:"+msg.toString());
//将client端标记和信道记录,为了做心跳监测
JSONObject msgJson = JSON.parseObject(msg.toString());
NettySocketHolder.put((String) msgJson.get("user"), (NioSocketChannel) ctx.channel());
ctx.write(jsonObject.toJSONString());
}
/**
* 从客户端收到新的数据、读取完成时调用
*
* @param ctx
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
System.out.println("channelReadComplete");
ctx.flush();
}
/**
* 当出现 Throwable 对象才会被调用,即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
*
* @param ctx
* @param cause
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException
{
System.out.println("exceptionCaught");
cause.printStackTrace();
ctx.close();//抛出异常,断开与客户端的连接
}
/**
* 客户端与服务端第一次建立连接时 执行
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException
{
super.channelActive(ctx);
ctx.channel().read();
InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = insocket.getAddress().getHostAddress();
//此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
System.out.println("channelActive:"+clientIp+ctx.name());
}
/**
* 客户端与服务端 断连时 执行
*
* @param ctx
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) {
NettySocketHolder.remove((NioSocketChannel) ctx.channel());
}
/**
* 服务端当read超时, 会调用这个方法
*
* @param ctx
* @param evt
* @throws Exception
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException
{
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
if (idleStateEvent.state() == IdleState.READER_IDLE) {
System.out.println("已经15秒没有收到信息!");
//向客户端发送消息
// ctx.close();//直接关闭,可以添加具体的业务处理逻辑
// ctx.writeAndFlush("HEART_BEAT").addListener(ChannelFutureListener.CLOSE_ON_FAILURE);//先给client发消息,未成功则断开连接
}
}
super.userEventTriggered(ctx, evt);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception{
System.out.println("channelRegistered");
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception{
System.out.println("channelUnregistered");
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception{
System.out.println("channelWritabilityChanged");
}
记录client标记与信道的类
public class NettySocketHolder {
private static final Map<String, NioSocketChannel> MAP = new ConcurrentHashMap<>(16);
public static void put(String user, NioSocketChannel socketChannel) {
MAP.put(user, socketChannel);
}
public static NioSocketChannel get(String user) {
return MAP.get(user);
}
public static Map<String, NioSocketChannel> getMAP() {
return MAP;
}
public static void remove(NioSocketChannel nioSocketChannel) {
MAP.entrySet().stream().filter(entry -> entry.getValue() == nioSocketChannel).forEach(entry -> MAP.remove(entry.getKey()));
}
}
编写netty的server
public class BootNettyServer {
public void bind(int port) {
/**
* 配置服务端的NIO线程组
* NioEventLoopGroup 是用来处理I/O操作的Reactor线程组
* bossGroup:用来接收进来的连接,workerGroup:用来处理已经被接收的连接,进行socketChannel的网络读写,
* bossGroup接收到连接后就会把连接信息注册到workerGroup
* workerGroup的EventLoopGroup默认的线程数是CPU核数的二倍
*/
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
/**
* ServerBootstrap 是一个启动NIO服务的辅助启动类
*/
ServerBootstrap serverBootstrap = new ServerBootstrap();
/**
* 设置group,将bossGroup, workerGroup线程组传递到ServerBootstrap
*/
serverBootstrap = serverBootstrap.group(bossGroup, workerGroup);
/**
* ServerSocketChannel是以NIO的selector为基础进行实现的,用来接收新的连接,这里告诉Channel通过NioServerSocketChannel获取新的连接
*/
serverBootstrap = serverBootstrap.channel(NioServerSocketChannel.class);
/**
* option是设置 bossGroup,childOption是设置workerGroup
* netty 默认数据包传输大小为1024字节, 设置它可以自动调整下一次缓冲区建立时分配的空间大小,避免内存的浪费 最小 初始化 最大 (根据生产环境实际情况来定)
* 使用对象池,重用缓冲区
*/
serverBootstrap = serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 10496, 1048576));
serverBootstrap = serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 10496, 1048576));
//保持长连接
serverBootstrap = serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
/**
* 设置 I/O处理类,主要用于网络I/O事件,记录日志,编码、解码消息
*/
serverBootstrap = serverBootstrap.childHandler(new BootNettyChannelInitializer());
System.out.println("netty server start success!");
/**
* 绑定端口,同步等待成功
*/
ChannelFuture f = serverBootstrap.bind(port).sync();
/**
* 等待服务器监听端口关闭
*/
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
} finally {
/**
* 退出,释放线程池资源
*/
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
端口绑定
在启动类里边修改
1、启动类实现 CommandLineRunner
2、绑定配置好的端口
@Value("${server.netty.netty-port}")
private int port;
3、重写run方法
@Override
public void run(String... args) throws Exception {
/**
* 使用异步注解方式启动netty服务端服务
*/
new BootNettyServer().bind(port);
}
注意
spring可以管理自身的bean注入,但netty中不能自动注入,若业务逻辑中要用到spring中的bean,通过@Autowired是注入不成功的,这边可以使用这种方式在这里插入代码片
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
在Netty中调用的方式:
@Autowired(required = false)
private static NettyService nettyService;//自己的service
static {
nettyService = SpringUtil.getBean(NettyService.class);
}
暂时用到的只有这些,其中有的代码是在网上找的,把自己需要的择出来,做笔记方便以后用,具体链接不记得了!