Netty练手项目-简单Http服务器

简单的设计思路就是,启动一个可以截断并处理Http请求的服务器代码。使用netty提供的boss线程与worker线程的模型,并使用netty的http解码器。自行编写了http url处理的部分。在接口层面,使用json作为格式。

初始化扫描会指定扫描controller.container下的类,使用了自定义Annotation并且单例的方式加载,未考虑太多细节就为了好玩。


接下来使用postman尝试调用接口。

一个简单的netty搭建的web服务就完成了。
package server; import handler.HttpServerHandler;
import initScan.InitialProcess;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec; /**
* Created by MacBook on 2019/7/14.
*/
public class ServerStarter { private EventLoopGroup boss ; private EventLoopGroup worker ; private int port; private static int DEFAULT_PORT = 8080; public ServerStarter(){
boss = new NioEventLoopGroup();
worker = new NioEventLoopGroup();
port = DEFAULT_PORT;
} public ServerStarter(int port){
this();
if(port < 0 || port > 65535){
throw new IllegalArgumentException("port:"+port+" is illegal");
}
this.port = port;
} public void startup() throws InterruptedException{ if(boss.isShutdown() || worker.isShutdown()){
throw new IllegalStateException("server was closed");
} // 初始化容器
InitialProcess initialProcess = new InitialProcess();
initialProcess.init(); ServerBootstrap serverBootstrap = new ServerBootstrap();
System.out.println("=====http server start ");
serverBootstrap.channel(NioServerSocketChannel.class)
.group(boss,worker)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.option(ChannelOption.SO_BACKLOG,1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast("http-decode",new HttpServerCodec());
socketChannel.pipeline().addLast(new HttpServerHandler());
}
}); ChannelFuture future = serverBootstrap.bind(port).sync(); System.out.println("server port listen:"+port); future.channel().closeFuture().sync(); shutDownGracefully();
} /**
* 关闭管道
*/
public void shutDownGracefully(){
this.boss.shutdownGracefully();
this.worker.shutdownGracefully();
} }
这是服务器启动的核心代码,首先初始化两个Nio线程组,把它们绑定到ServerBootstrap里,并添加Handler。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import controller.Properties;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import response.BaseResponse; import java.lang.reflect.Method; /**
* Created by MacBook on 2019/7/14.
*/
public class HttpServerHandler extends ChannelInboundHandlerAdapter{ @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg instanceof HttpRequest){
HttpRequest request = (HttpRequest)msg;
// boolean keepAlive = HttpUtil.isKeepAlive(request); System.out.println("http request method :"+request.method());
System.out.println("http request uri : "+request.uri()); Object controller = Properties.urlController.get(request.uri());
Method m = Properties.urlMethod.get(request.uri());
if(controller == null){
FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE); }else {
FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
Object result = m.invoke(controller); httpResponse.content().writeBytes(JSON.toJSONString(result,SerializerFeature.WriteMapNullValue).getBytes()); ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
} }
}
}
这是处理器的代码,在经过第一个Http解码器之后,进来的对象msg已经被转化为HttpRequest了。
Netty练手项目-简单Http服务器的更多相关文章
- 微信小程序初体验,入门练手项目--通讯录,后台是阿里云服务器(一)
内容: 一.前言 二.相关概念 三.开始工作 四.启动项目起来 五.项目结构 六.设计理念 七.路由 八.部署线上后端服务 同步交流学习社区: https://www.mwcxs.top/page/4 ...
- web前端学习部落22群分享给需要前端练手项目
前端学习还是很有趣的,可以较快的上手然后自己开发一些好玩的项目来练手,网上也可以一抓一大把关于前端开发的小项目,可是还是有新手在学习的时候不知道可以做什么,以及怎么做,因此,就整理了一些前端项目教程, ...
- Python之路【第二十四篇】:Python学习路径及练手项目合集
Python学习路径及练手项目合集 Wayne Shi· 2 个月前 参照:https://zhuanlan.zhihu.com/p/23561159 更多文章欢迎关注专栏:学习编程. 本系列Py ...
- 推荐:一个适合于Python新手的入门练手项目
随着人工智能的兴起,国内掀起了一股Python学习热潮,入门级编程语言,大多选择Python,有经验的程序员,也开始学习Python,正所谓是人生苦短,我用Python 有个Python入门练手项目, ...
- 80个Python练手项目列表
80个Python练手项目列表 我若将死,给孩子留遗言,只留一句话:Repetition is the mother of all learning重复是学习之母.他们将来长大,学知识,技巧.爱情 ...
- webpack练手项目之easySlide(三):commonChunks(转)
Hello,大家好. 在之前两篇文章中: webpack练手项目之easySlide(一):初探webpack webpack练手项目之easySlide(二):代码分割 与大家分享了webpack的 ...
- webpack练手项目之easySlide(二):代码分割(转)
在上一篇 webpack练手项目之easySlide(一):初探webpack 中我们一起为大家介绍了webpack的基本用法,使用webpack对前端代码进行模块化打包. 但是乍一看webpack ...
- 练手项目:利用pygame库编写射击游戏
本项目使用pygame模块编写了射击游戏,目的在于训练自己的Python基本功.了解中小型程序框架以及学习代码重构等.游戏具有一定的可玩性,感兴趣的可以试一下. 项目说明:出自<Python编程 ...
- 适合Python的5大练手项目, 你练了么?
在练手项目的选择上,还存在疑问?不知道要从哪种项目先下手? 首先有两点建议: 最好不要写太应用的程序练手,要思考什么更像是知识,老只会写写爬虫是无用的,但是完全不写也不行. 对于练手的程序,要注意简化 ...
随机推荐
- 在SuSE安装wifidog认证服务器和网关
在SuSE安装认证服务器和网关 在openSuSE 10.3安装wifidog 认证服务器和网关在同台设备中安装完毕.以下是openSuSE的详细安装指南.这个安装是非常初级的,所以请验证或更正. - ...
- B站动手学深度学习第十八课:seq2seq(编码器和解码器)和注意力机制
from mxnet import nd h_forward = nd.array([1,2]) h_backward = nd.array([3,4]) h_bi = nd.concat(h_for ...
- docker搭建pxc
1.下载镜像 curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://f1361db2.m.daocloud.i ...
- maria 忘记密码
1.找到mariadb配置文件命令:find / -name my.cnf 备注:一般是在 /etc/my.cnf 2.修改配置文件 在MariaDB配置文件/etc/my.cnf的[mysqld]配 ...
- centos 系统字体库安装中文字体
一,centos系统默认不支持中文字体的,需要手动安装windows系统中的中文字体库到centos中. 首先,将windows系统中的字体拷贝出来: windows:打开C:\Windows\Fon ...
- PJzhang:CVE-2019-14287 sudo权限绕过漏洞复现
猫宁!!! 参考链接:Ms08067实验室公众号 sudo 1.8.28版本之前有漏洞. 更新完kali linux,deepin截图工具失效,只能用自带的,不能划重点. 看一下sudo版本,1.8. ...
- LCA cogs 2450 2048 1588
t1 2450距离 链接:http://cogs.pro:8081/cogs/problem/problem.php?pid=vSNNNVqga [题目描述] 在一个村子里有N个房子,一些双向的路连接 ...
- CSP考试策略
准备 带好手表,身份证,准考证,文具,和矿泉水(热水). 考试之前 如果时间比较充足,可以重启测试保护是否解开. 调整显示屏亮度,检查键盘.鼠标. 关掉拓展名隐藏. 写个简单程序测试是否有异常,测试对 ...
- GIP画图
世界坐标:相对于winform窗体来说的, 页面坐标:相对于控件的 设置坐标:相对于显示器 获得Graphics对象一般有两种方式: 1.控件.CreateGraphics();//通过该方式创建后要 ...
- Python与用户的交互
目录 Python与用户的交互 为什么交互 如何交互 Python2 中的交互 Python与用户的交互 为什么交互 让我们来回顾计算机的发明有何意义,计算机的发明是为了奴役计算机,解放劳动力.假设我 ...