Netty是由JBOSS提供的一个java开源框架,现为 Github上的独立项目。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。
也就是说,Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程。
新建springboot项目,并在项目以来中导入netty包,用fastjson包处理jsonStr。
io.netty netty-all 4.1.42.Final com.alibaba.fastjson2 fastjson2 2.0.16
创建netty相关配置信息文件
# netty 配置
netty:# boss线程数量boss: 4# worker线程数量worker: 2# 连接超时时间timeout: 6000# 服务器主端口port: 18023# 服务器备用端口portSalve: 18026# 服务器地址host: 127.0.0.1
@ConfigurationProperties(prefix = "netty")注解读取配置文件中的netty配置,通过反射注入值,需要在实体类中提供对应的setter和getter方法。
@ConfigurationProperties(prefix = "netty")对应的实体类属性名称不要求一定相同,只需保证“set”字符串拼接配置文件的属性和setter方法名相同即可。
@Configuration
@ConfigurationProperties(prefix = "netty")
public class NettyProperties {/*** boss线程数量*/private Integer boss;/*** worker线程数量*/private Integer worker;/*** 连接超时时间*/private Integer timeout = 30000;/*** 服务器主端口*/private Integer port = 18023;/*** 服务器备用端口*/private Integer portSalve = 18026;/*** 服务器地址 默认为本地*/private String host = "127.0.0.1";// setter、getter 。。。。
}
@Configuration
@EnableConfigurationProperties
public class NettyConfig {final NettyProperties nettyProperties;public NettyConfig(NettyProperties nettyProperties) {this.nettyProperties = nettyProperties;}/*** boss线程池-进行客户端连接** @return*/@Beanpublic NioEventLoopGroup boosGroup() {return new NioEventLoopGroup(nettyProperties.getBoss());}/*** worker线程池-进行业务处理** @return*/@Beanpublic NioEventLoopGroup workerGroup() {return new NioEventLoopGroup(nettyProperties.getWorker());}/*** 服务端启动器,监听客户端连接** @return*/@Beanpublic ServerBootstrap serverBootstrap() {ServerBootstrap serverBootstrap = new ServerBootstrap()// 指定使用的线程组.group(boosGroup(), workerGroup())// 指定使用的通道.channel(NioServerSocketChannel.class)// 指定连接超时时间.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyProperties.getTimeout())// 指定worker处理器.childHandler(new NettyServerHandler());return serverBootstrap;}
}
##@##分割符,通过DelimiterBasedFrameDecoder来处理拆包沾包问题;MessageDecodeHandler将接收消息解码处理成对象实例;MessageEncodeHandler将发送消息增加分割符后并编码;ServerListenerHandler根据消息类型对应处理不同消息。public class NettyServerHandler extends ChannelInitializer {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {// 数据分割符String delimiterStr = "##@##";ByteBuf delimiter = Unpooled.copiedBuffer(delimiterStr.getBytes());ChannelPipeline pipeline = socketChannel.pipeline();// 使用自定义处理拆包/沾包,并且每次查找的最大长度为1024字节pipeline.addLast(new DelimiterBasedFrameDecoder(1024, delimiter));// 将上一步解码后的数据转码为Message实例pipeline.addLast(new MessageDecodeHandler());// 对发送客户端的数据进行编码,并添加数据分隔符pipeline.addLast(new MessageEncodeHandler(delimiterStr));// 对数据进行最终处理pipeline.addLast(new ServerListenerHandler());}
}
public class MessageDecodeHandler extends ByteToMessageDecoder {@Overrideprotected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List
public class Message {/*** 数据长度*/private Integer len;/*** 接收的通讯数据body*/private String content;/*** 消息类型*/private Integer msgType;public Message(Object object) {String str = object.toString();JSONObject jsonObject = JSONObject.parseObject(str);msgType = Integer.valueOf(jsonObject.getString("msg_type"));content = jsonObject.getString("body");len = str.length();}public String toJsonString() {return "{" +"\"msg_type\": " + msgType + ",\n" +"\"body\": " + content +"}";}// setter、getter 。。。。
}
public class MessageEncodeHandler extends MessageToByteEncoder {// 数据分割符String delimiter;public MessageEncodeHandler(String delimiter) {this.delimiter = delimiter;}@Overrideprotected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf out) throws Exception {out.writeBytes((message.toJsonString() + delimiter).getBytes(CharsetUtil.UTF_8));}
}
public class ServerListenerHandler extends SimpleChannelInboundHandler {private static final Logger log = LoggerFactory.getLogger(ServerListenerHandler.class);/*** 设备接入连接时处理** @param ctx*/@Overridepublic void handlerAdded(ChannelHandlerContext ctx) {log.info("有新的连接:[{}]", ctx.channel().id().asLongText());}/*** 数据处理** @param ctx* @param msg*/@Overrideprotected void channelRead0(ChannelHandlerContext ctx, Message msg) {// 获取消息实例中的消息体String content = msg.getContent();// 对不同消息类型进行处理MessageEnum type = MessageEnum.getStructureEnum(msg);switch (type) {case CONNECT:// TODO 心跳消息处理case STATE:// TODO 设备状态default:System.out.println(type.content + "消息内容" + content);}}/*** 设备下线处理** @param ctx*/@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) {log.info("设备下线了:{}", ctx.channel().id().asLongText());}/*** 设备连接异常处理** @param ctx* @param cause*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {// 打印异常log.info("异常:{}", cause.getMessage());// 关闭连接ctx.close();}
}
public enum MessageEnum {CONNECT(1, "心跳消息"),STATE(2, "设备状态");public final Integer type;public final String content;MessageEnum(Integer type, String content) {this.type = type;this.content = content;}// case中判断使用public static MessageEnum getStructureEnum(Message msg) {Integer type = Optional.ofNullable(msg).map(Message::getMsgType).orElse(0);if (type == 0) {return null;} else {List objectEnums = Arrays.stream(MessageEnum.values()).filter((item) -> item.getType() == type).distinct().collect(Collectors.toList());if (objectEnums.size() > 0) {return objectEnums.get(0);}return null;}}// setter、getter。。。。
}
到此Netty整个配置已经完成,但如果要跟随springboot一起启动,仍需要做一些配置。
@Component
public class NettyServerBoot {private static final Logger log = LoggerFactory.getLogger(NettyServerBoot.class);@ResourceNioEventLoopGroup boosGroup;@ResourceNioEventLoopGroup workerGroup;final ServerBootstrap serverBootstrap;final NettyProperties nettyProperties;public NettyServerBoot(ServerBootstrap serverBootstrap, NettyProperties nettyProperties) {this.serverBootstrap = serverBootstrap;this.nettyProperties = nettyProperties;}/*** 启动netty** @throws InterruptedException*/@PostConstructpublic void start() throws InterruptedException {// 绑定端口启动serverBootstrap.bind(nettyProperties.getPort()).sync();// 备用端口serverBootstrap.bind(nettyProperties.getPortSalve()).sync();log.info("启动Netty: {},{}", nettyProperties.getPort(), nettyProperties.getPortSalve());}/*** 关闭netty*/@PreDestroypublic void close() {log.info("关闭Netty");boosGroup.shutdownGracefully();workerGroup.shutdownGracefully();}
}
增加NettyServerBoot配置后,启动application时,netty服务端会跟随一起启动。

同时,在springboot关闭前,会先销毁netty服务。

https://github.com/BerBai/JavaExample/tree/master/netty