Netty实战:Netty优雅的创建高性能TCP服务器(附源码)
前言
Springboot使用Netty优雅、快速的创建高性能TCP服务器,适合作为开发脚手架进行二次开发。
1. 前置准备
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- netty包 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.75.Final</version>
</dependency>
<!-- 常用JSON工具包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
- 编写yml配置文件
# tcp
netty:
server:
host: 127.0.0.1
port: 20000
# 传输模式linux上开启会有更高的性能
use-epoll: false
# 日记配置
logging:
level:
# 开启debug日记打印
com.netty: debug
- 读取YML中的服务配置
/**
* 读取YML中的服务配置
*
* @author ding
*/
@Configuration
@ConfigurationProperties(prefix = ServerProperties.PREFIX)
@Data
public class ServerProperties {
public static final String PREFIX = "netty.server";
/**
* 服务器ip
*/
private String ip;
/**
* 服务器端口
*/
private Integer port;
/**
* 传输模式linux上开启会有更高的性能
*/
private boolean useEpoll;
}
2. 消息处理器
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 消息处理,单例启动
*
* @author qiding
*/
@Slf4j
@Component
@ChannelHandler.Sharable
@RequiredArgsConstructor
public class MessageHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
log.debug("\n");
log.debug("channelId:" + ctx.channel().id());
log.debug("收到消息:{}", message);
// 回复客户端
ctx.writeAndFlush("服务器接收成功!");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
log.debug("\n");
log.debug("开始连接");
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
log.debug("\n");
log.debug("成功建立连接,channelId:{}", ctx.channel().id());
super.channelActive(ctx);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
log.debug("心跳事件时触发");
if (evt instanceof IdleStateEvent) {
log.debug("发送心跳");
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
} else {
super.userEventTriggered(ctx, evt);
}
}
}
3. 重写通道初始化类
添加我们需要的解码器,这里添加了String解码器和编码器
import com.netty.server.handler.MessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Netty 通道初始化
*
* @author qiding
*/
@Component
@RequiredArgsConstructor
public class ChannelInit extends ChannelInitializer<SocketChannel> {
private final MessageHandler messageHandler;
@Override
protected void initChannel(SocketChannel channel) {
channel.pipeline()
// 心跳时间
.addLast("idle", new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS))
// 添加解码器
.addLast(new StringDecoder())
// 添加编码器
.addLast(new StringEncoder())
// 添加消息处理器
.addLast("messageHandler", messageHandler);
}
}
4. 核心服务
- 接口
public interface ITcpServer {
/**
* 主启动程序,初始化参数
*
* @throws Exception 初始化异常
*/
void start() throws Exception;
/**
* 优雅的结束服务器
*
* @throws InterruptedException 提前中断异常
*/
@PreDestroy
void destroy() throws InterruptedException;
}
- 服务实现
/**
* 启动 Server
*
* @author qiding
*/
@Component
@Slf4j
@RequiredArgsConstructor
public class TcpServer implements ITcpServer {
private final ChannelInit channelInit;
private final ServerProperties serverProperties;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
@Override
public void start() {
log.info("初始化 TCP server ...");
bossGroup = serverProperties.isUseEpoll() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
workerGroup = serverProperties.isUseEpoll() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
this.tcpServer();
}
/**
* 初始化
*/
private void tcpServer() {
try {
new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(serverProperties.isUseEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(serverProperties.getPort()))
// 配置 编码器、解码器、业务处理
.childHandler(channelInit)
// tcp缓冲区
.option(ChannelOption.SO_BACKLOG, 128)
// 将网络数据积累到一定的数量后,服务器端才发送出去,会造成一定的延迟。希望服务是低延迟的,建议将TCP_NODELAY设置为true
.childOption(ChannelOption.TCP_NODELAY, false)
// 保持长连接
.childOption(ChannelOption.SO_KEEPALIVE, true)
// 绑定端口,开始接收进来的连接
.bind().sync();
log.info("tcpServer启动成功!开始监听端口:{}", serverProperties.getPort());
} catch (Exception e) {
e.printStackTrace();
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
/**
* 销毁
*/
@PreDestroy
@Override
public void destroy() {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
5. 效果预览
- 启动类添加启动方法
/**
* @author ding
*/
@SpringBootApplication
@RequiredArgsConstructor
public class NettyServerApplication implements ApplicationRunner {
private final TcpServer tcpServer;
public static void main(String[] args) {
SpringApplication.run(NettyServerApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
tcpServer.start();
}
}
运行

打开tcp客户端工具进行测试

6. 添加通道管理,给指定的客户端发送消息
为了给指定客户端发送消息,我们需要设置一个登录机制,保存登录成功的客户端ID和频道的关系
- 编写通道存储类
/**
* 频道信息存储
* <p>
* 封装netty的频道存储,客户端id和频道双向绑定
*
* @author qiding
*/
@Slf4j
public class ChannelStore {
/**
* 频道绑定 key
*/
private final static AttributeKey<Object> CLIENT_ID = AttributeKey.valueOf("clientId");
/**
* 客户端和频道绑定
*/
private final static ConcurrentHashMap<String, ChannelId> CLIENT_CHANNEL_MAP = new ConcurrentHashMap<>(16);
/**
* 存储频道
*/
public final static ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
/**
* 重入锁
*/
private static final Lock LOCK = new ReentrantLock();
/**
* 获取单机连接数量
*/
public static int getLocalConnectCount() {
return CHANNEL_GROUP.size();
}
/**
* 获取绑定的通道数量(测试用)
*/
public static int getBindCount() {
return CLIENT_CHANNEL_MAP.size();
}
/**
* 绑定频道和客户端id
*
* @param ctx 连接频道
* @param clientId 用户id
*/
public static void bind(ChannelHandlerContext ctx, String clientId) {
LOCK.lock();
try {
// 释放旧的连接
closeAndClean(clientId);
// 绑定客户端id到频道上
ctx.channel().attr(CLIENT_ID).set(clientId);
// 双向保存客户端id和频道
CLIENT_CHANNEL_MAP.put(clientId, ctx.channel().id());
// 保存频道
CHANNEL_GROUP.add(ctx.channel());
} finally {
LOCK.unlock();
}
}
/**
* 是否已登录
*/
public static boolean isAuth(ChannelHandlerContext ctx) {
return !StringUtil.isNullOrEmpty(getClientId(ctx));
}
/**
* 获取客户端id
*
* @param ctx 连接频道
*/
public static String getClientId(ChannelHandlerContext ctx) {
return ctx.channel().hasAttr(CLIENT_ID) ? (String) ctx.channel().attr(CLIENT_ID).get() : "";
}
/**
* 获取频道
*
* @param clientId 客户端id
*/
public static Channel getChannel(String clientId) {
return Optional.of(CLIENT_CHANNEL_MAP.containsKey(clientId))
.filter(Boolean::booleanValue)
.map(b -> CLIENT_CHANNEL_MAP.get(clientId))
.map(CHANNEL_GROUP::find)
.orElse(null);
}
/**
* 释放连接和资源
* CLIENT_CHANNEL_MAP 需要释放
* CHANNEL_GROUP 不需要释放,netty会自动帮我们移除
*
* @param clientId 客户端id
*/
public static void closeAndClean(String clientId) {
// 清除绑定关系
Optional.of(CLIENT_CHANNEL_MAP.containsKey(clientId))
.filter(Boolean::booleanValue)
.ifPresent(oldChannel -> CLIENT_CHANNEL_MAP.remove(clientId));
// 若存在旧连接,则关闭旧连接,相同clientId,不允许重复连接
Optional.ofNullable(getChannel(clientId))
.ifPresent(ChannelOutboundInvoker::close);
}
public static void closeAndClean(ChannelHandlerContext ctx) {
closeAndClean(getClientId(ctx));
}
}
- 配置登录机制
我们在消息处理器 MessageHandler 中修改channelRead0方法,模拟登录
@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
log.debug("\n");
log.debug("channelId:" + ctx.channel().id());
log.debug("收到消息:{}", message);
// 判断是否未登录
if (!ChannelStore.isAuth(ctx)) {
// 登录逻辑自行实现,我这里为了演示把第一次发送的消息作为客户端ID
String clientId = message.trim();
ChannelStore.bind(ctx, clientId);
log.debug("登录成功");
ctx.writeAndFlush("login successfully");
return;
}
// 回复客户端
ctx.writeAndFlush("ok");
}
/**
* 指定客户端发送
*
* @param clientId 其它已成功登录的客户端
* @param message 消息
*/
public void sendByClientId(String clientId, String message) {
Channel channel = ChannelStore.getChannel(clientId);
channel.writeAndFlush(message);
}
调用sendByClientId即可给已登录的其它客户端发送消息了。
7. 源码分享
- Springboot-cli开发脚手架,集合各种常用框架使用案例,完善的文档,致力于让开发者快速搭建基础环境并让应用跑起来。
- 项目源码国内gitee地址
- 项目源码github地址
Netty实战:Netty优雅的创建高性能TCP服务器(附源码)的更多相关文章
- Netty学习:ChannelHandler执行顺序详解,附源码分析
近日学习Netty,在看书和实践的时候对于书上只言片语的那些话不是十分懂,导致尝试写例子的时候遭遇各种不顺,比如decoder和encoder还有HttpObjectAggregator的添加顺序,研 ...
- 【TCP/IP】TCP服务器并发处理&源码
前言 本笔记记录的是 单个服务端并发式处理多个客户端. 下次有空在发个 单线程多个服务端并发式处理多种客户端.其实就是本笔记的一个改良版,用到select() / poll() / epoll(). ...
- SpringCloud-服务注册与实现-Eureka创建服务注册中心(附源码下载)
场景 SpringCloud学习之运行第一个Eureka程序: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/90611451 S ...
- python爬虫实战——自动下载百度图片(文末附源码)
用Python制作一个下载图片神器 前言 这个想法是怎么来的? 很简单,就是不想一张一张的下载图片,嫌太慢. 在很久很久以前,我比较喜欢收集各种动漫的壁纸,作为一个漫迷,自然是能收集多少就收集多少.小 ...
- 【Storm】Storm实战之频繁二项集挖掘(附源码)
一.前言 针对大叔据实时处理的入门,除了使用WordCount示例之外,还需要相对更深入点的示例来理解Storm,因此,本篇博文利用Storm实现了频繁项集挖掘的案例,以方便更好的入门Storm. 二 ...
- Python爬虫实战,完整的思路和步骤(附源码)
前言 小的时候心中总有十万个为什么类似的问题,今天带大家爬取一个问答类的网站. 本堂课使用正则表达式对文本类的数据进行提取,正则表达式是数据提取的通用方法. 环境介绍: python 3.6 pych ...
- selenium实战:窗口化爬取*宝数据(附源码链接)
完整代码&火狐浏览器驱动下载链接:https://pan.baidu.com/s/1pc8HnHNY8BvZLvNOdHwHBw 提取码:4c08 双十一刚过,想着某宝的信息看起来有些少很难做 ...
- SpringCloud-服务注册与实现-Eureka创建服务提供者(附源码下载)
场景 SpringCloud-服务注册与实现-Eureka创建服务注册中心(附源码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...
- 高性能TcpServer(C#) - 2.创建高性能Socket服务器SocketAsyncEventArgs的实现(IOCP)
高性能TcpServer(C#) - 1.网络通信协议 高性能TcpServer(C#) - 2.创建高性能Socket服务器SocketAsyncEventArgs的实现(IOCP) 高性能TcpS ...
- Scala 深入浅出实战经典 第61讲:Scala中隐式参数与隐式转换的联合使用实战详解及其在Spark中的应用源码解析
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载: 百度云盘:http://pan.baidu.com/s/1c0noOt ...
随机推荐
- Flex 弹性布局备忘录
概述 Flex 是 Flexible Box 的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性 这也是我目前用的最多的一种布局方案,相比Grid布局此种布局方案相对较简单, ...
- Javascript之常用尺寸、位置获取
标签: js 缘起 平时在开发中或多或少需要去获取元素尺寸,特此记录常用的尺寸获取方案. 常用相关尺寸 窗口可视尺寸 测试地址 /** * 获取窗口可视尺寸 */ function getWindow ...
- Docker跨主机跨服务器迁移
主要作用: 就是让配置好的容器,可以得到复用,后面用到得的时候就不需要重新配置. 其中涉及到的命令有: docker commit 将容器保存为镜像 docker save -o 将镜像备份为tar ...
- 腾讯云 TStor 统一存储通过信通院首批文件存储基础能力评测
在大数据上升为国家战略背景下,当前我国各行业.各领域正积极提升数据资源掌控能力和深度价值挖掘能力.存储作为数据基础设施建设的关键支柱,在国民经济发展过程中的重要性日益凸显. 2022年6月16日,中国 ...
- 云数据备份 | CDN 日志备份最佳实践
前言 内容分发网络(Content Delivery Network,CDN),是在现有 Internet 中增加的一层新的网络架构,可以有效降低用户访问延迟,提升可用性. CDN 按照小时粒度对 ...
- EverEdit插件-CHM助手:一种免费、高效的CHM手册制作方式
1 EverEdit插件-CHM助手:一种免费.高效的CHM手册制作方式 1.1 前言 业界制作CHM手册的工具多如牛毛,高贵的商业工具如:HelpNDoc.Help+Manual.HelpSmi ...
- 【网站搭建】开源社区Flarum搭建记录
环境 服务器系统:腾讯云 OpenCloudOS 宝塔版本:免费版8.0.1 Nginx:1.24.0 MySQL:5.7.42 PHP:8.1.21 萌狼蓝天 2023年8月7日 PHP设置 1.安 ...
- 【Web前端】【疑难杂症】轮播图图片自适应显示问题(bootstrap3轮播图)
关键代码 html <!-- 轮播图开始--> <div id="header" class="carousel slide"> < ...
- Qt编写手机端视频播放器/推流工具/Onvif工具
一.视频播放器 同时支持多种解码内核,包括qmedia内核(Qt4/Qt5/Qt6).ffmpeg内核(ffmpeg2/ffmpeg3/ffmpeg4/ffmpeg5/ffmpeg6).vlc内核(v ...
- 23种设计模式实战:重学Java设计模式
23种设计模式实战PDF: 链接:https://pan.baidu.com/s/1XfjkBt19G7jZQfwk5wAV3w 提取码:1234