netty之Netty与SpringBoot整合

ops/2024/10/10 18:45:06/

前言

在实际的开发中,我们需要对netty服务进行更多的操作,包括;获取它的状态信息、启动/停止、对客户端用户强制下线等等,为此我们需要把netty服务加入到web系统中。
MyChannelInitializer

java">public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel channel) {// 基于换行符号channel.pipeline().addLast(new LineBasedFrameDecoder(1024));// 解码转String,注意调整自己的编码格式GBK、UTF-8channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));// 解码转String,注意调整自己的编码格式GBK、UTF-8channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));// 在管道中添加我们自己的接收数据实现方法channel.pipeline().addLast(new MyServerHandler());}}

MyServerHandler

java">public class MyServerHandler extends ChannelInboundHandlerAdapter {private Logger logger = LoggerFactory.getLogger(MyServerHandler.class);/*** 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {SocketChannel channel = (SocketChannel) ctx.channel();logger.info("链接报告开始");logger.info("链接报告信息:有一客户端链接到本服务端");logger.info("链接报告IP:{}", channel.localAddress().getHostString());logger.info("链接报告Port:{}", channel.localAddress().getPort());logger.info("链接报告完毕");//通知客户端链接建立成功String str = "通知客户端链接建立成功" + " " + new Date() + " " + channel.localAddress().getHostString() + "\r\n";ctx.writeAndFlush(str);}/*** 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据*/@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {logger.info("客户端断开链接{}", ctx.channel().localAddress().toString());}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//接收msg消息{与上一章节相比,此处已经不需要自己进行解码}logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 服务端接收到消息:" + msg);//通知客户端链消息发送成功String str = "服务端收到:" + new Date() + " " + msg + "\r\n";ctx.writeAndFlush(str);}/*** 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();logger.info("异常信息:\r\n" + cause.getMessage());}}
java">@Component("nettyServer")
public class NettyServer {private Logger logger = LoggerFactory.getLogger(NettyServer.class);//配置服务端NIO线程组private final EventLoopGroup parentGroup = new NioEventLoopGroup(); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));private final EventLoopGroup childGroup = new NioEventLoopGroup();private Channel channel;public ChannelFuture bing(InetSocketAddress address) {ChannelFuture channelFuture = null;try {ServerBootstrap b = new ServerBootstrap();b.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)    //非阻塞模式.option(ChannelOption.SO_BACKLOG, 128).childHandler(new MyChannelInitializer());channelFuture = b.bind(address).syncUninterruptibly();channel = channelFuture.channel();} catch (Exception e) {logger.error(e.getMessage());} finally {if (null != channelFuture && channelFuture.isSuccess()) {logger.info("server start done. {关注明哥 获取源码}");} else {logger.error("server start error. {关注明哥 获取源码}");}}return channelFuture;}public void destroy() {if (null == channel) return;channel.close();parentGroup.shutdownGracefully();childGroup.shutdownGracefully();}public Channel getChannel() {return channel;}}
java">@SpringBootApplication
@ComponentScan("com.lm")
public class NettyApplication implements CommandLineRunner {@Value("${netty.host}")private String host;@Value("${netty.port}")private int port;@Autowiredprivate NettyServer nettyServer;public static void main(String[] args) {SpringApplication.run(NettyApplication.class, args);}@Overridepublic void run(String... args) throws Exception {InetSocketAddress address = new InetSocketAddress(host, port);ChannelFuture channelFuture = nettyServer.bing(address);Runtime.getRuntime().addShutdownHook(new Thread(() -> nettyServer.destroy()));channelFuture.channel().closeFuture().syncUninterruptibly();}}
java">@RestController
@RequestMapping(value = "/nettyserver", method = RequestMethod.GET)
public class NettyController {@Resourceprivate NettyServer nettyServer;@RequestMapping("/localAddress")public String localAddress() {return "nettyServer localAddress " + nettyServer.getChannel().localAddress();}@RequestMapping("/isOpen")public String isOpen() {return "nettyServer isOpen " + nettyServer.getChannel().isOpen();}}

测试结果
启动SpringBoot *NettyApplication.main >run
在这里插入图片描述
启动ApiTest
在这里插入图片描述
Web访问 *http://localhost:8080/nettyserver/localAddress
在这里插入图片描述
Web访问 *http://localhost:8080/nettyserver/isOpen
在这里插入图片描述
好了到这里就结束了netty之Netty与SpringBoot整合的学习,大家一定要跟着动手操作起来。需要的源码的 可si我获取;


http://www.ppmy.cn/ops/123603.html

相关文章

Unity3D Shader的阴影部分法线效果详解

在Unity3D开发中&#xff0c;阴影处理是提升场景真实感和视觉质量的重要一环。法线贴图&#xff08;Normal Mapping&#xff09;作为一种高效的纹理映射技术&#xff0c;在增强模型表面细节和凹凸感方面扮演着重要角色。本文将详细解析UnityShader中阴影部分的法线效果&#xf…

毕设分享 基于协同过滤的电影推荐系统

文章目录 0 简介1 设计概要2 课题背景和目的3 协同过滤算法原理3.1 基于用户的协同过滤推荐算法实现原理3.1.1 步骤13.1.2 步骤23.1.3 步骤33.1.4 步骤4 4 系统实现4.1 开发环境4.2 系统功能描述4.3 系统数据流程4.3.1 用户端数据流程4.3.2 管理员端数据流程 4.4 系统功能设计 …

20240904 华为笔试 二叉树消消乐

文章目录 题目解题思路代码BUG 代码最终代码题目 题目描述 给定原始二叉树和参照二叉树(输入的二叉树均为满二叉树,二叉树节点的值范围为[1,1000],二叉树的深度不超过1000),现对原始二叉树和参照二又树中相同层级目值相同的节点进行消除,消除规则为原始二叉树和参照二又树中…

Git初识

Git仓库 Git概念&#xff1a;一个免费开源&#xff0c;分布式的代码版本控制系统&#xff0c;帮助开发团队维护代码 作用&#xff1a;记录代码内容&#xff0c;切换代码版本&#xff0c;多人开发时高效合并代码内容 Git仓库&#xff1a;记录文件状态内容的地方&#xff0c;存…

在使用visual studio 2022,运行程序时弹窗:“ 此任务要求应用程序具有提升的权限“

系列文章目录 文章目录 系列文章目录前言一、问题原因二、解决方法1.第一种解决方法2.第二种解决方法 前言 在使用visual studio 2022&#xff0c;运行程序时弹窗&#xff1a;" 此任务要求应用程序具有提升的权限"&#xff0c;每次都要再次点击“使用其他凭证重新启…

基于阻塞队列及环形队列的生产消费模型

目录 条件变量函数 等待条件满足 阻塞队列 升级版 信号量 POSIX信号量 环形队列 条件变量函数 等待条件满足 int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex); 参数&#xff1a; cond&#xff1a;要在这个条件变量上等待 mutex…

C++——继承

目录 引言 继承的概念和定义 1.继承的概念 2.继承的定义 2.1 继承的语法形式 2.2 继承中类的叫法 2.3 继承后的子类成员访问权限 基类与派生类的赋值转换 1.派生类对象赋值给基类对象 2.派生类对象的引用赋值给基类对象 3.派生类对象的指针赋值给基类对象 4.基类指…

jpa String index out of range: 0

ORM Spring Data Jpa 查询报错信息 原因&#xff1a;数据库字段设置为char类型&#xff0c;但是该字段为空字符串 参考&#xff1a;https://stackoverflow.com/questions/24380846/hibernate-sql-exception-java-lang-stringindexoutofboundsexception-string-index java.lang…