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 个气体传感器的所有采样值&…...

【kafka】Golang实现分布式Masscan任务调度系统
要求: 输出两个程序,一个命令行程序(命令行参数用flag)和一个服务端程序。 命令行程序支持通过命令行参数配置下发IP或IP段、端口、扫描带宽,然后将消息推送到kafka里面。 服务端程序: 从kafka消费者接收…...

基于FPGA的PID算法学习———实现PID比例控制算法
基于FPGA的PID算法学习 前言一、PID算法分析二、PID仿真分析1. PID代码2.PI代码3.P代码4.顶层5.测试文件6.仿真波形 总结 前言 学习内容:参考网站: PID算法控制 PID即:Proportional(比例)、Integral(积分&…...
AtCoder 第409场初级竞赛 A~E题解
A Conflict 【题目链接】 原题链接:A - Conflict 【考点】 枚举 【题目大意】 找到是否有两人都想要的物品。 【解析】 遍历两端字符串,只有在同时为 o 时输出 Yes 并结束程序,否则输出 No。 【难度】 GESP三级 【代码参考】 #i…...

为什么需要建设工程项目管理?工程项目管理有哪些亮点功能?
在建筑行业,项目管理的重要性不言而喻。随着工程规模的扩大、技术复杂度的提升,传统的管理模式已经难以满足现代工程的需求。过去,许多企业依赖手工记录、口头沟通和分散的信息管理,导致效率低下、成本失控、风险频发。例如&#…...
鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院查看报告小程序
一、开发环境准备 工具安装: 下载安装DevEco Studio 4.0(支持HarmonyOS 5)配置HarmonyOS SDK 5.0确保Node.js版本≥14 项目初始化: ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...
JDK 17 新特性
#JDK 17 新特性 /**************** 文本块 *****************/ python/scala中早就支持,不稀奇 String json “”" { “name”: “Java”, “version”: 17 } “”"; /**************** Switch 语句 -> 表达式 *****************/ 挺好的ÿ…...
python报错No module named ‘tensorflow.keras‘
是由于不同版本的tensorflow下的keras所在的路径不同,结合所安装的tensorflow的目录结构修改from语句即可。 原语句: from tensorflow.keras.layers import Conv1D, MaxPooling1D, LSTM, Dense 修改后: from tensorflow.python.keras.lay…...

处理vxe-table 表尾数据是单独一个接口,表格tableData数据更新后,需要点击两下,表尾才是正确的
修改bug思路: 分别把 tabledata 和 表尾相关数据 console.log() 发现 更新数据先后顺序不对 settimeout延迟查询表格接口 ——测试可行 升级↑:async await 等接口返回后再开始下一个接口查询 ________________________________________________________…...
Vite中定义@软链接
在webpack中可以直接通过符号表示src路径,但是vite中默认不可以。 如何实现: vite中提供了resolve.alias:通过别名在指向一个具体的路径 在vite.config.js中 import { join } from pathexport default defineConfig({plugins: [vue()],//…...
Linux系统部署KES
1、安装准备 1.版本说明V008R006C009B0014 V008:是version产品的大版本。 R006:是release产品特性版本。 C009:是通用版 B0014:是build开发过程中的构建版本2.硬件要求 #安全版和企业版 内存:1GB 以上 硬盘…...