Springboot+Netty
目录
一、netty入门
二、启动方式
三、netty服务启动类
四、handler链
五、具体业务
六、 线程或者非spring管理的bean中获取spring管理的bean
七、效果
一、netty入门
Netty-导学_哔哩哔哩_bilibili
入门视频量比较大,最主要是了解netty的架构
netty官网:
Netty.docs: User guide for 4.x
对springboot有入门级别会启动项目设置bean基本就可以完成了
maven依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.7</version><relativePath/></parent>
<properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.95.Final</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.10.1</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-extension</artifactId><version>3.5.3.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.15</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-collections4</artifactId><version>4.4</version></dependency></dependencies></project>
二、启动方式
以web方式启动,tomcat占用80端口 netty占用9002端口
import com.xnetty.config.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;/*** description: 以web的方式进行项目启动*/
@SpringBootApplication
@Slf4j
public class XNettyApplication {public static void main(String[] args) throws Exception {ApplicationContext context = SpringApplication.run(XNettyApplication.class, args);NettyServer nettyServer = context.getBean(NettyServer.class);nettyServer.start();log.info("XNettyApplication finish start....");}
}
属性配置文件application.properties中配置
server.port=80
netty.server.port=9002
三、netty服务启动类
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;/*** description:*/
@Component
@Slf4j
public class NettyServer {public void start() throws Exception {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(8);executor.setMaxPoolSize(200);executor.setQueueCapacity(10000);executor.setKeepAliveSeconds(60);executor.setRejectedExecutionHandler((r, executor1) -> {try {executor1.getQueue().put(r);log.info("执行了拒绝策略.....");} catch (InterruptedException e) {log.error("加入队列异常:{}", e.getMessage());}});executor.setThreadGroupName("netty_request");executor.initialize();NioEventLoopGroup bossGroup = new NioEventLoopGroup(16);NioEventLoopGroup workGroup = new NioEventLoopGroup(16);try {ChannelFuture channelFuture = new ServerBootstrap().group(bossGroup, workGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).option(ChannelOption.ALLOCATOR, ByteBufAllocator.DEFAULT).childHandler(new ServerInit(executor)).bind("0.0.0.0", port).sync();Channel channel = channelFuture.channel();channel.closeFuture().sync();} finally {bossGroup.shutdownGracefully();workGroup.shutdownGracefully();}}@Value("${netty.server.port}")private int port;}
四、handler链
import com.xnetty.service.ReadRequestHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;/*** description:*/
@Service
public class ServerInit extends ChannelInitializer<NioSocketChannel> {private ThreadPoolTaskExecutor executor;public ServerInit(ThreadPoolTaskExecutor executor) {this.executor = executor;}@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {ch.pipeline().addLast(new IdleStateHandler(0, 0, 30 * 3, TimeUnit.SECONDS)).addLast(new HttpServerCodec()).addLast(new HttpObjectAggregator(5 * 1024 * 1024)) //大小为10M.addLast(new MpHandler(executor));}
}
五、具体业务
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;/*** description:*/
public class MpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {ThreadPoolTaskExecutor executor;public MpHandler(ThreadPoolTaskExecutor executor) {this.executor = executor;}@Overrideprotected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {String uri = request.uri();if (uri.equals("/hello")) {executor.execute(()->{FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, Unpooled.copiedBuffer("hello word", CharsetUtil.UTF_8)); // Unpooled.wrappedBuffer(responseJson)response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8"); // HttpHeaderValues.TEXT_PLAIN.toString()response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());if (HttpUtil.isKeepAlive(request)) {response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);}ctx.writeAndFlush(response);});} else {executor.execute(() -> {FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, Unpooled.copiedBuffer("请求成功....", CharsetUtil.UTF_8)); // Unpooled.wrappedBuffer(responseJson)response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8"); // HttpHeaderValues.TEXT_PLAIN.toString()response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());if (HttpUtil.isKeepAlive(request)) {response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);}ctx.writeAndFlush(response);});}}
}
六、 线程或者非spring管理的bean中获取spring管理的bean
至于如何在非spring管理的bean中获取spring管理的对象或者在线程中获取spring管理的bean,则自定义一个beanutils获取
如下
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;@Component
public class SpringBeanUtils implements ApplicationContextAware {private static ApplicationContext context;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {context = applicationContext;}public static Object getBean(String name) {return context.getBean(name);}public static <T> T getBean(Class<T> clazz) {return context.getBean(clazz);}public static <T> T getBeanByName(String beanName, Class<T> clazz) {return context.getBean(beanName, clazz);}}
七、效果
七http://localhost:9002/hello

相关文章:
Springboot+Netty
目录 一、netty入门 二、启动方式 三、netty服务启动类 四、handler链 五、具体业务 六、 线程或者非spring管理的bean中获取spring管理的bean 七、效果 一、netty入门 Netty-导学_哔哩哔哩_bilibili 入门视频量比较大,最主要是了解netty的架构 netty官网&am…...
window.location.href is not a function
在使用uniapp跳转到外部页面时,使用window.location.href报错 解决: 当出现"window.location.href is not a function"的错误时,这通常是因为在某些浏览器中,window.location.href被视为只读属性,而不是函…...
STM32+FPGA的导常振动信号采集存储系统
摘 要 : 针 对 工 厂 重 要 设 备 运 输 途 中 可 能 损 坏 的情 况 , 本 文 设计 了一 套 采 用 STM32F103+F࿳…...
Eclipse memory analyzer 分析GC dump日志定位代码问题
1、问题描述: 使用命令 jstat -gcutil [pid] 查看JVM GC日志,发现生产系统频繁FullGC,大概几分钟一次,而且系统响应速度变慢很多 再使用 free -g 查看服务器内存全部占用,猜测是内存溢出了 2、导出dump日志 jmap -du…...
DSA之图(3):图的遍历
文章目录 0 图的遍历1 图的遍历方法1.1 深度优先搜索DFS1.1.1 DFS的思想1.1.2 邻接矩阵DFS的实现1.1.3 邻接矩阵DFS的代码实现1.1.4 非连通图的DFS遍历1.1.5 DFS算法效率分析 1.2 广度优先搜索BFS1.2.1 BFS的思想(连通图)1.2.2 BFS的思想(非连…...
从零开始学习 Java:简单易懂的入门指南之for循环(四)
java基础知识 流程控制语句1.1 流程控制语句分类1.2 顺序结构 判断语句:if语句2.1 if语句格式1练习1:老丈人选女婿练习2:考试奖励第一种格式的细节: 2.2 if语句格式2练习1:吃饭练习2:影院选座 2.3 if语句格…...
Android 之 http/https原理和机制
http---HyperTextTransfer Protocol 超文本传输协议 超文本-文本、HTML http的工作方式 c/b结构 如浏览器访问到服务器。 即发送请求->相应。 Url-Http报文 http://www.baidu.com/path 协议类型:http or https or websocket 服务器地址 BaseUrl 路径&…...
mybatis源码研究、搭建mybatis源码运行的环境
文章底部有个人公众号:热爱技术的小郑。主要分享开发知识、有兴趣的可以关注一手。 前提 研究源码、对我们的技术提高还是很有帮助的。简单的源码建议从mybatis入手。涉及到的设计模式不是很多。需要下载mybatis的源码和父工程依赖。注意下载的mybatis中的父工程依…...
【算法基础:搜索与图论】3.5 求最小生成树算法(PrimKruskal)
文章目录 最小生成树介绍朴素Prim算法算法思路⭐例题:858. Prim算法求最小生成树 Kruskal算法算法思路⭐例题:859. Kruskal算法求最小生成树 最小生成树介绍 最小生成树 有关树的定义 生成子图:生成子图是从原图中选取部分节点以及这些节点…...
扩展Ceph集群实现高可用
...
代码随想录 DAY45
class Solution { public: int climbStairs(int n) { vector<int>dp(n1,0); dp[0]1; for(int j0;j<n;j){ for(int i1;i<2;i){ if(j>i) dp[j]dp[j-i]; } } return dp[n]; } }; 这个题还是说想清楚 这个因为有1和2 阶的情况 所以i就是从1开始遍历 然后小于等于…...
Centos报错:[Errno 12] Cannot allocate memory
执行一个脚本刚开始正常,后面就报[Errno 12] Cannot allocate memory 如果内存不足,可能需要增加交换内存。或者可能根本没有启用交换。可以通过以下方式检查您的交换: sudo swapon -s如果它为空,则表示您没有启用任何交换。添加 1GB 交换…...
手把手教你怎么写顺序表
目录 一、顺序表有什么功能? 二、实现顺序表的各个功能 1.前置准备 2.初始化顺序表 3.顺序表扩容 4.打印顺序表 5.增加顺序表成员 5.1尾增 5.2头增 6.删除顺序表中成员的内容 6.1尾删 6.2头删 7.查找成员 8.修改(替换) 9.插入(在目标位置插入成员) 10.定…...
FPGA中RAM的结构理解
FPGA中RAM的结构理解 看代码的过程中对RAM的结构不是很理解,搞脑子一片浆糊,反复推算,好不容易理清了思路,记录下来,防止忘记。开辟的RAM总容量为128bytes,数据的位宽为32位(即一个单元有32bit…...
家庭用的无线洗地机到底好不好用?2023洗地机品牌排行榜前十名
无线洗地机在清洁使用的时候非常便捷,多功能于一体能够轻轻松松就拖扫完全家,不需要多余的先扫再拖,浪费时间还非常的劳累。那么有什么靠谱并且质量也有保障的无线洗地机推荐吗?为了给想要选购洗地机的小伙伴提供一些参考…...
[React]常见Hook实现之useUpdateEffect
useUpdateEffect是一个自定义的React Hook,用于在组件更新时执行副作用。它的实现原理如下: useEffect和useLayoutEffect:useUpdateEffect内部使用useEffect或useLayoutEffect来注册副作用函数。这两个Hook函数都接受一个回调函数和依赖项数…...
为什么视频画质会变差,如何提升视频画质清晰度。
在数字时代,视频已经成为我们生活中不可或缺的一部分。然而,随着视频的传输和处理过程中的多次压缩,画质损失逐渐凸显,影响了我们对影像的真实感受。为了让视频画质更加清晰、逼真,我们需要采取一些措施来保护和修复视…...
【uni-app2.0】实现登录页记住密码功能
使用uni-app的uni.setStorageSync()和uni.getStorageSync()方法来存储和读取密码 在登录页中添加一个记住密码的u-checkbox选项,并在data里面添加一个rememberPwd的布尔值,在每次点击记住密码change的时候来记录用户的选择 <u-checkbox-group place…...
IDEA live templates
surround 在SQL的xml里 可以修改变量 官方文档 CDATA not null <if test"$SELECTION$ ! null and $SELECTION$ ! "> and $VAR1$ #{$SELECTION$} </if>not null like mysql <if test"$SELECTION$ ! null and $SELECTION$ ! "> and…...
电子鼻毕业论文
面向压埋探测的人体代谢气体识别方法的研究与应用 实现对非目标气体的检测 数据预处理 (1a)标准化 将采集到的数据先进行变换,统一数量级。其中,xij为第j个传感器的第i个采样值;xj为第 j 个气体传感器的所有采样值&…...
C++实现分布式网络通信框架RPC(3)--rpc调用端
目录 一、前言 二、UserServiceRpc_Stub 三、 CallMethod方法的重写 头文件 实现 四、rpc调用端的调用 实现 五、 google::protobuf::RpcController *controller 头文件 实现 六、总结 一、前言 在前边的文章中,我们已经大致实现了rpc服务端的各项功能代…...
【HarmonyOS 5.0】DevEco Testing:鸿蒙应用质量保障的终极武器
——全方位测试解决方案与代码实战 一、工具定位与核心能力 DevEco Testing是HarmonyOS官方推出的一体化测试平台,覆盖应用全生命周期测试需求,主要提供五大核心能力: 测试类型检测目标关键指标功能体验基…...
【Go】3、Go语言进阶与依赖管理
前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课,做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程,它的核心机制是 Goroutine 协程、Channel 通道,并基于CSP(Communicating Sequential Processes࿰…...
Android15默认授权浮窗权限
我们经常有那种需求,客户需要定制的apk集成在ROM中,并且默认授予其【显示在其他应用的上层】权限,也就是我们常说的浮窗权限,那么我们就可以通过以下方法在wms、ams等系统服务的systemReady()方法中调用即可实现预置应用默认授权浮…...
汇编常见指令
汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX(不访问内存)XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...
网络编程(UDP编程)
思维导图 UDP基础编程(单播) 1.流程图 服务器:短信的接收方 创建套接字 (socket)-----------------------------------------》有手机指定网络信息-----------------------------------------------》有号码绑定套接字 (bind)--------------…...
selenium学习实战【Python爬虫】
selenium学习实战【Python爬虫】 文章目录 selenium学习实战【Python爬虫】一、声明二、学习目标三、安装依赖3.1 安装selenium库3.2 安装浏览器驱动3.2.1 查看Edge版本3.2.2 驱动安装 四、代码讲解4.1 配置浏览器4.2 加载更多4.3 寻找内容4.4 完整代码 五、报告文件爬取5.1 提…...
学校时钟系统,标准考场时钟系统,AI亮相2025高考,赛思时钟系统为教育公平筑起“精准防线”
2025年#高考 将在近日拉开帷幕,#AI 监考一度冲上热搜。当AI深度融入高考,#时间同步 不再是辅助功能,而是决定AI监考系统成败的“生命线”。 AI亮相2025高考,40种异常行为0.5秒精准识别 2025年高考即将拉开帷幕,江西、…...
听写流程自动化实践,轻量级教育辅助
随着智能教育工具的发展,越来越多的传统学习方式正在被数字化、自动化所优化。听写作为语文、英语等学科中重要的基础训练形式,也迎来了更高效的解决方案。 这是一款轻量但功能强大的听写辅助工具。它是基于本地词库与可选在线语音引擎构建,…...
让回归模型不再被异常值“带跑偏“,MSE和Cauchy损失函数在噪声数据环境下的实战对比
在机器学习的回归分析中,损失函数的选择对模型性能具有决定性影响。均方误差(MSE)作为经典的损失函数,在处理干净数据时表现优异,但在面对包含异常值的噪声数据时,其对大误差的二次惩罚机制往往导致模型参数…...
