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

8 | 爬虫解析利器 PyQuery 的使用
文章目录 爬虫解析利器 PyQuery 的使用简介安装基本用法初始化查找元素遍历元素修改元素练习题练习题 1练习题 2答案练习题 1练习题 2总结爬虫解析利器 PyQuery 的使用 简介 PyQuery 是一个 Python 的库,它是 jQuery 的 Python 实现。PyQuery 可以让开发者使用类似于 jQuery…...

2023年 React 最佳学习路线
CSS CSS JavaScript JavaScript TypeScript 目前没有找到比其他文档好很多的文档地址 可以先看官网 React 新版 React 官方文档无敌 React React-router-dom V5 V6 Webpack webpack Antd antd...

使用 ChatGPT 进行研究的先进技术
在这篇文章中,您将探索改进您研究的先进技术。尤其, 分析和解释研究数据进行文献综述并找出研究差距废话不多说直接开始吧!!! 分析和解释研究数据 一家小企业主希望分析客户满意度数据以改善客户服务。他们使用包含 10…...

Java-API简析_java.net.Proxy类(基于 Latest JDK)(浅析源码)
【版权声明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权) https://blog.csdn.net/m0_69908381/article/details/131881661 出自【进步*于辰的博客】 因为我发现目前,我对Java-API的学习意识比较薄弱…...

磁盘问题和解决: fsck,gdisk,fdisk等
错误: Resize inode not valid 对于gpt分区的硬盘一般fsck只能检查分区, 不能用于检查整个硬盘, 但是如果对硬盘设备运行时遇到这样的错误 $ sudo fsck -n /dev/sdc fsck from util-linux 2.37.2 e2fsck 1.46.5 (30-Dec-2021) GW1.5T was not cleanly unmounted, check force…...

基于深度学习的高精度六类海船检测识别系统(PyTorch+Pyside6+YOLOv5模型)
摘要:基于深度学习的高精度六类海船检测识别系统可用于日常生活中检测与定位海船目标(散装货船(bulk cargo carrier)、集装箱船(container ship)、渔船(fishing boat)、普通货船&…...

【React Native】学习记录(一)——环境搭建
Expo是一套工具,库和服务,可让您通过编写JavaScript来构建原生iOS和Android应用程序。 一开始学习的时候直接使用的是expo。 npx create-expo-app my-appcd my-appnpm run start接下来需要搭建安卓和IOS端(为此特意换成了苹果电脑)…...

Java 设计模式 - 简单工厂模式 - 创建对象的简便之道
简单工厂模式是一种创建型设计模式,它提供了一种简单的方式来创建对象,而无需暴露对象创建的逻辑。在本篇博客中,我们将深入了解简单工厂模式的概念、实现方式以及如何在Java中使用它来创建对象。 为什么使用简单工厂模式? 在软…...

C# 事件
C# 事件 1.事件概述 事件(Event) 基本上说是一个用户操作,如按键、点击、鼠标移动等等,或者是一些提示信息,如系统生成的通知。应用程序需要在事件发生时响应事件。例如,中断。 C# 中使用事件机制实现线程…...

网络:TCP/IP协议
1. OSI七层参考模型 应用层 表示层 会话层 传输层 网络层 数据链路层 物理层 2. TCP/IP模型 应用层 传输层 网络层 数据链路层 物理层 3. 各链路层对应的名称 应用层对应的是协议数据单元 传输层对应的是数据段 网络层对应的是数据包 链路层对应的是数据帧 物理层对应的是比特…...