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

XML Group端口详解
在XML数据映射过程中,经常需要对数据进行分组聚合操作。例如,当处理包含多个物料明细的XML文件时,可能需要将相同物料号的明细归为一组,或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码,增加了开…...

以光量子为例,详解量子获取方式
光量子技术获取量子比特可在室温下进行。该方式有望通过与名为硅光子学(silicon photonics)的光波导(optical waveguide)芯片制造技术和光纤等光通信技术相结合来实现量子计算机。量子力学中,光既是波又是粒子。光子本…...

day36-多路IO复用
一、基本概念 (服务器多客户端模型) 定义:单线程或单进程同时监测若干个文件描述符是否可以执行IO操作的能力 作用:应用程序通常需要处理来自多条事件流中的事件,比如我现在用的电脑,需要同时处理键盘鼠标…...

MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
macos brew国内镜像加速方法 brew install 加速formula.jws.json下载慢加速 🍺 最新版brew安装慢到怀疑人生?别怕,教你轻松起飞! 最近Homebrew更新至最新版,每次执行 brew 命令时都会自动从官方地址 https://formulae.…...
LOOI机器人的技术实现解析:从手势识别到边缘检测
LOOI机器人作为一款创新的AI硬件产品,通过将智能手机转变为具有情感交互能力的桌面机器人,展示了前沿AI技术与传统硬件设计的完美结合。作为AI与玩具领域的专家,我将全面解析LOOI的技术实现架构,特别是其手势识别、物体识别和环境…...

【堆垛策略】设计方法
堆垛策略的设计是积木堆叠系统的核心,直接影响堆叠的稳定性、效率和容错能力。以下是分层次的堆垛策略设计方法,涵盖基础规则、优化算法和容错机制: 1. 基础堆垛规则 (1) 物理稳定性优先 重心原则: 大尺寸/重量积木在下…...
[USACO23FEB] Bakery S
题目描述 Bessie 开了一家面包店! 在她的面包店里,Bessie 有一个烤箱,可以在 t C t_C tC 的时间内生产一块饼干或在 t M t_M tM 单位时间内生产一块松糕。 ( 1 ≤ t C , t M ≤ 10 9 ) (1 \le t_C,t_M \le 10^9) (1≤tC,tM≤109)。由于空间…...

密码学基础——SM4算法
博客主页:christine-rr-CSDN博客 专栏主页:密码学 📌 【今日更新】📌 对称密码算法——SM4 目录 一、国密SM系列算法概述 二、SM4算法 2.1算法背景 2.2算法特点 2.3 基本部件 2.3.1 S盒 2.3.2 非线性变换 编辑…...
大数据治理的常见方式
大数据治理的常见方式 大数据治理是确保数据质量、安全性和可用性的系统性方法,以下是几种常见的治理方式: 1. 数据质量管理 核心方法: 数据校验:建立数据校验规则(格式、范围、一致性等)数据清洗&…...

海云安高敏捷信创白盒SCAP入选《中国网络安全细分领域产品名录》
近日,嘶吼安全产业研究院发布《中国网络安全细分领域产品名录》,海云安高敏捷信创白盒(SCAP)成功入选软件供应链安全领域产品名录。 在数字化转型加速的今天,网络安全已成为企业生存与发展的核心基石,为了解…...