netty构建http服务器
Netty 是一个高性能的异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。要使用 Netty 搭建一个支持 HTTP 方法(GET, POST, PUT, DELETE)的 HTTP 服务器,可以按照以下步骤进行操作。
准备工作
- 添加依赖:确保你的项目中包含了 Netty 的相关依赖。
- Java版本:确保你使用的 Java 版本支持 Netty,一般推荐使用 Java 8 或更高版本。
添加 Maven 依赖
在你的 pom.xml 文件中添加以下依赖:
<dependencies><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.95.Final</version></dependency>
</dependencies>
创建 HTTP 服务器
下面是一个简单的示例,展示了如何创建一个支持 GET, POST, PUT, DELETE 方法的 HTTP 服务器。
1. 定义 HTTP 请求处理器
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;public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {if (!req.decoderResult().isSuccess()) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}// 根据请求类型处理switch (req.method()) {case GET:handleGet(ctx, req);break;case POST:handlePost(ctx, req);break;case PUT:handlePut(ctx, req);break;case DELETE:handleDelete(ctx, req);break;default:sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.METHOD_NOT_ALLOWED));break;}}private void handleGet(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 GET 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a GET response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void handlePost(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 POST 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a POST response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void handlePut(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 PUT 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a PUT response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void handleDelete(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 DELETE 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a DELETE response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {if (res.status().code() != 200) {ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);res.content().writeBytes(buf);buf.release();HttpHeaders.setContentLength(res, res.content().readableBytes());}// Generate an error page if response status code is not 200 (OK).if (res.status().code() != 200) {ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);res.content().writeBytes(buf);buf.release();}// Send the response and close the connection if necessary.ChannelFuture f = ctx.channel().writeAndFlush(res);if (!HttpHeaders.isKeepAlive(req) || res.status().code() != 200) {f.addListener(ChannelFutureListener.CLOSE);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}
2. 启动服务器
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;public class HttpServer {public static void main(String[] args) throws InterruptedException {int port = 8080; // 选择一个端口EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new HttpServerInitializer());ChannelFuture f = b.bind(port).sync();System.out.println("HTTP server started on port " + port);f.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}
3. 初始化 Channel
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline p = ch.pipeline();p.addLast(new HttpResponseEncoder());p.addLast(new HttpRequestDecoder());p.addLast(new HttpObjectAggregator(65536));p.addLast(new HttpServerHandler());}
}
以上代码提供了一个基本的 HTTP 服务器框架,你可以根据需要添加具体的业务逻辑处理,如错误处理、日志记录、文件上传等高级功能。
在 Netty 中处理文件上传通常涉及到对 HTTP 请求中的 multipart/form-data 类型的解析。这种类型的请求通常用于上传文件和其他表单数据。下面介绍如何使用 Netty 和第三方库来处理文件上传。
第三方库
对于文件上传的支持,我们可以使用 netty-http2 项目中的 netty-codec-http2 依赖或者使用 netty-file-upload 项目中的 netty-codec-http 依赖,后者提供了更直接的方式来处理文件上传。我们将使用 netty-codec-http 依赖。
首先,在你的 pom.xml 文件中添加如下依赖:
<dependencies><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.95.Final</version></dependency><dependency><groupId>io.netty</groupId><artifactId>netty-codec-http</artifactId><version>4.1.95.Final</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency>
</dependencies>
文件上传处理
- HTTP 请求解析器:使用 HttpDataFactory和HttpPostRequestDecoder解析上传的数据。
- 文件保存:定义一个方法来保存上传的文件。
更新 HttpServerHandler
 
import io.netty.buffer.ByteBuf;
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.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {if (!req.decoderResult().isSuccess()) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}switch (req.method()) {case GET:handleGet(ctx, req);break;case POST:handlePost(ctx, req);break;case PUT:handlePut(ctx, req);break;case DELETE:handleDelete(ctx, req);break;default:sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.METHOD_NOT_ALLOWED));break;}}private void handlePost(ChannelHandlerContext ctx, FullHttpRequest req) {if (!req.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);if (contentType.contains("multipart/form-data")) {handleFileUpload(ctx, req);} else {handleRegularPost(ctx, req);}}private void handleFileUpload(ChannelHandlerContext ctx, FullHttpRequest req) {FileUpload fileUpload = new FileUpload(new DiskFileItemFactory());HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fileUpload, req);while (true) {try {HttpPostRequestDecoder.State state = decoder.decode(ctx.channel(), req, ctx.alloc().buffer());if (state == HttpPostRequestDecoder.State.END_OF_MESSAGE) {break;}if (state == HttpPostRequestDecoder.State.CHUNKED_INPUT) {decoder.offer(req);}} catch (HttpPostRequestDecoder.EndOfDataDecoderException e) {break;} catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}}FileItemIterator iterator = decoder.getBodyHttpData();while (iterator.hasNext()) {FileItemStream item = iterator.next();if (item.isFormField()) {// Handle form fields here} else {saveUploadedFile(item, "/tmp/uploaded"); // Save the file to disk}}FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("File uploaded successfully.", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void saveUploadedFile(FileItemStream item, String uploadDir) throws IOException {Path targetPath = Path.of(uploadDir, item.getName());Files.createDirectories(targetPath.getParent());try (FileItemStream.ItemStream stream = item.openStream()) {Files.copy(stream, targetPath, StandardCopyOption.REPLACE_EXISTING);}}private void handleRegularPost(ChannelHandlerContext ctx, FullHttpRequest req) {// Handle regular POST data hereFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a POST response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {// ... [same as before]}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}
注意事项
- 在这个示例中,我们使用了 commons-fileupload库来处理multipart/form-data数据。
- 上传的文件被保存到 /tmp/uploaded目录下。你需要确保这个目录存在并且有适当的权限。
- 我们使用了 DiskFileItemFactory和FileUpload来处理文件上传。
- 如果上传的文件非常大,你可能需要调整 DiskFileItemFactory的配置以适应你的需求。
以上代码提供了一个基本的文件上传处理机制。你可以根据实际需要进一步扩展和优化。例如,可以添加文件大小限制、文件类型检查等功能。
相关文章:
netty构建http服务器
Netty 是一个高性能的异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。要使用 Netty 搭建一个支持 HTTP 方法(GET, POST, PUT, DELETE)的 HTTP 服务器,可以按照以下步骤进行操作。 准备工作 添加依赖…...
Docker中安装Kafka和Kafka UI管理界面
Kafka 简介 Apache Kafka 是一个分布式流处理平台,主要用于构建实时数据管道和流应用。它最初由LinkedIn开发,并于2011年开源,之后成为Apache项目的一部分。Kafka的核心概念和功能包括: 发布与订阅消息系统:Kafka允许用户发布和订阅消息流。高吞吐量:Kafka能够处理大量数…...
 
防火墙——SNAT和DNAT策略的原理及应用、防火墙规则的备份、还原和抓包
防火墙——SNAT和DNAT策略的原理及应用、防火墙规则的备份、还原和抓包 💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识&…...
C# 冒泡排序
栏目总目录 概念 冒泡排序(Bubble Sort)是一种简单的排序算法,它通过重复遍历待排序的数列,比较每对相邻的项,并在顺序错误时交换它们的位置,直到没有需要交换的项为止。由于排序过程中小数逐渐“浮”到前…...
 
网络传输层——UDP与TCP
前言: 1.国际网络体系结构: OSI模型: open system interconnect 理论模型 1977 国际标准化组织 各种不同体系结构的计算机能在世界范围内互联成网。 应用层:要传输的数据信息,如文件传输,电子邮件等…...
 
Hype 4 Pro for Mac:专业级HTML5动画制作利器
Hype 4 Pro for Mac是一款专为Mac用户设计的专业级HTML5动画制作软件,它集动画制作、交互设计于一身,为用户提供了一种全新的、高效的动画制作体验。 该软件拥有直观易用的界面和强大的功能,支持多种设计元素,如滚动、旋转、缩放…...
C++ STL remove, remove_if 用法
一:功能 移除序列中(满足给定条件)的元素,该操作并不是真的将元素删除,而是序列的size不变,只是更新了迭代器,该函数会返回最后一个未删除元素的位置。 二:用法 #include <vect…...
HarmonyOS NEXT 开发之ArkTS基础入门
ArkTS 是 HarmonyOS NEXT 的开发语言,它基于 TypeScript 并进行了扩展和优化。以下是一些基础语法知识点、示例用法及注意事项。 一、ArkTS 简介 ArkTS 是一种基于 TypeScript 的编程语言,主要用于 HarmonyOS 应用的 UI 界面和业务逻辑开发。它在 Type…...
 
UE5 C++跑酷练习(Part2)
一.首先GameMode里有Actor数组,组装直线路,和左右路 #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "RunGANGameMode.generated.h"UCLASS(minimalapi) class ARunGANGameMode : public AG…...
 
从0开始搭建vue + flask 旅游景点数据分析系统(二):搭建基础框架
这一期目标是把系统的布局给搭建起来,采用一个非常简单的后端管理风格,可以参考官方的页面 https://element.eleme.cn/#/zh-CN/component/container 下面我们开始搭建,首先,安装一下vue-router,element-ui npm insta…...
【过滤器 vs 拦截器】SpringBoot中过滤器与拦截器:明智选择的艺术(如何在项目中做出明智选择)
文章目录 SpringBoot 过滤器 vs 拦截器过滤器 (Filter)定义特点使用场景实现步骤创建过滤器类注册过滤器(可选,如果不使用 WebFilter 注解) 拦截器 (Interceptor)定义特点使用场景实现步骤创建拦截器类注册拦截器 过滤器与拦截器的比较实际项…...
 
2024-06学习笔记
1.事务与数据库链接的占用 如果用Transactional注解,那在第一次与数据库交互的时候,就会打开数据库链接,再整个方法执行完,才会关闭数据库链接。 即使后边用的事务传播是required_new,那之前的事务也是被挂起,不会被…...
 
【VUE】封装一个追随鼠标的漂浮组件框架
红色箭头代表鼠标位置,蓝色区域跟随鼠标出现,鼠标进行其他操作的时候,蓝色区域隐藏。 vue全码 <template><divmousemove"updatePosition"mouseleave"hideDiv"class"container":style"{ positi…...
mapstruct与lombok结合使用
问题 如果同时使用mapstruct与lombok,需要多添加一个lombok支持mapstruct的依赖库。 解决 <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId> </dependency><dependency><groupId&…...
【SpringBoot】Web开发之URL映射
RequestMapping("/getDataById/{id}") public String getDataById(PathVariable("id") Long id){ return "getDataById:"id; }46 如果URL中的参数名称与方法中的参数名称一致,则可以简化为: RequestMapping("/get…...
 
对递归的一些理解。力扣206题:翻转链表
今天在刷力扣的时候,在写一道翻转链表的题目的过程中,在尝试使用递归解决该问题的时候,第一版代码却每次都返回的是null,这个错误让我尝试去debug了一下,最终找出了问题,并且让我对递归有了一些更深的理解&…...
Kafka面试三道题
针对Kafka的面试题,从简单到困难,我可以给出以下三道题目: 1. Kafka的基本概念与优势 问题:请简要介绍Kafka是什么,并说明它相比传统消息队列的优势有哪些? 答案: Kafka定义:Apa…...
 
C/C++编程-算法学习-数字滤波器
数字滤波器 一阶低通滤波器结论推导11. 基本公式推导2. 截止频率 和 采样频率 推导 实现 二阶低通滤波器实现1实现2 一阶低通滤波器 结论 其基本原理基于以下公式: o u t p u t [ n ] α ∗ i n p u t [ n ] ( 1 − α ) ∗ o u t p u t [ n − 1 ] output[n] …...
 
maven介绍 搭建Nexus3(maven私服搭建)
Maven是一个强大的项目管理工具,它基于项目对象模型(POM:Project Object Model)的概念,通过XML格式的配置文件(pom.xml)来管理项目的构建 Maven确实可以被视为一种工程管理工具或项目自动化构…...
 
电商项目之如何判断线程池是否执行完所有任务
文章目录 1 问题背景2 前言3 4种常用的方法4 代码4.1 isTerminated()4.2 线程池的任务总数是否等于已执行的任务数4.3 CountDownLatch计数器4.4 CyclicBarrier计数器 1 问题背景 真实生产环境的电商项目,常使用线程池应用于执行大批量操作达到高性能的效果。应用场景…...
KubeSphere 容器平台高可用:环境搭建与可视化操作指南
Linux_k8s篇 欢迎来到Linux的世界,看笔记好好学多敲多打,每个人都是大神! 题目:KubeSphere 容器平台高可用:环境搭建与可视化操作指南 版本号: 1.0,0 作者: 老王要学习 日期: 2025.06.05 适用环境: Ubuntu22 文档说…...
谷歌浏览器插件
项目中有时候会用到插件 sync-cookie-extension1.0.0:开发环境同步测试 cookie 至 localhost,便于本地请求服务携带 cookie 参考地址:https://juejin.cn/post/7139354571712757767 里面有源码下载下来,加在到扩展即可使用FeHelp…...
在鸿蒙HarmonyOS 5中实现抖音风格的点赞功能
下面我将详细介绍如何使用HarmonyOS SDK在HarmonyOS 5中实现类似抖音的点赞功能,包括动画效果、数据同步和交互优化。 1. 基础点赞功能实现 1.1 创建数据模型 // VideoModel.ets export class VideoModel {id: string "";title: string ""…...
C++ 基础特性深度解析
目录 引言 一、命名空间(namespace) C 中的命名空间 与 C 语言的对比 二、缺省参数 C 中的缺省参数 与 C 语言的对比 三、引用(reference) C 中的引用 与 C 语言的对比 四、inline(内联函数…...
vue3 定时器-定义全局方法 vue+ts
1.创建ts文件 路径:src/utils/timer.ts 完整代码: import { onUnmounted } from vuetype TimerCallback (...args: any[]) > voidexport function useGlobalTimer() {const timers: Map<number, NodeJS.Timeout> new Map()// 创建定时器con…...
Spring AI 入门:Java 开发者的生成式 AI 实践之路
一、Spring AI 简介 在人工智能技术快速迭代的今天,Spring AI 作为 Spring 生态系统的新生力量,正在成为 Java 开发者拥抱生成式 AI 的最佳选择。该框架通过模块化设计实现了与主流 AI 服务(如 OpenAI、Anthropic)的无缝对接&…...
 
安宝特方案丨船舶智造的“AR+AI+作业标准化管理解决方案”(装配)
船舶制造装配管理现状:装配工作依赖人工经验,装配工人凭借长期实践积累的操作技巧完成零部件组装。企业通常制定了装配作业指导书,但在实际执行中,工人对指导书的理解和遵循程度参差不齐。 船舶装配过程中的挑战与需求 挑战 (1…...
在鸿蒙HarmonyOS 5中使用DevEco Studio实现企业微信功能
1. 开发环境准备 安装DevEco Studio 3.1: 从华为开发者官网下载最新版DevEco Studio安装HarmonyOS 5.0 SDK 项目配置: // module.json5 {"module": {"requestPermissions": [{"name": "ohos.permis…...
 
【从零开始学习JVM | 第四篇】类加载器和双亲委派机制(高频面试题)
前言: 双亲委派机制对于面试这块来说非常重要,在实际开发中也是经常遇见需要打破双亲委派的需求,今天我们一起来探索一下什么是双亲委派机制,在此之前我们先介绍一下类的加载器。 目录 编辑 前言: 类加载器 1. …...
 
MySQL:分区的基本使用
目录 一、什么是分区二、有什么作用三、分类四、创建分区五、删除分区 一、什么是分区 MySQL 分区(Partitioning)是一种将单张表的数据逻辑上拆分成多个物理部分的技术。这些物理部分(分区)可以独立存储、管理和优化,…...
