简单的设计思路就是,启动一个可以截断并处理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服务器的更多相关文章

  1. 微信小程序初体验,入门练手项目--通讯录,后台是阿里云服务器(一)

    内容: 一.前言 二.相关概念 三.开始工作 四.启动项目起来 五.项目结构 六.设计理念 七.路由 八.部署线上后端服务 同步交流学习社区: https://www.mwcxs.top/page/4 ...

  2. web前端学习部落22群分享给需要前端练手项目

    前端学习还是很有趣的,可以较快的上手然后自己开发一些好玩的项目来练手,网上也可以一抓一大把关于前端开发的小项目,可是还是有新手在学习的时候不知道可以做什么,以及怎么做,因此,就整理了一些前端项目教程, ...

  3. Python之路【第二十四篇】:Python学习路径及练手项目合集

      Python学习路径及练手项目合集 Wayne Shi· 2 个月前 参照:https://zhuanlan.zhihu.com/p/23561159 更多文章欢迎关注专栏:学习编程. 本系列Py ...

  4. 推荐:一个适合于Python新手的入门练手项目

    随着人工智能的兴起,国内掀起了一股Python学习热潮,入门级编程语言,大多选择Python,有经验的程序员,也开始学习Python,正所谓是人生苦短,我用Python 有个Python入门练手项目, ...

  5. 80个Python练手项目列表

    80个Python练手项目列表   我若将死,给孩子留遗言,只留一句话:Repetition is the mother of all learning重复是学习之母.他们将来长大,学知识,技巧.爱情 ...

  6. webpack练手项目之easySlide(三):commonChunks(转)

    Hello,大家好. 在之前两篇文章中: webpack练手项目之easySlide(一):初探webpack webpack练手项目之easySlide(二):代码分割 与大家分享了webpack的 ...

  7. webpack练手项目之easySlide(二):代码分割(转)

    在上一篇 webpack练手项目之easySlide(一):初探webpack  中我们一起为大家介绍了webpack的基本用法,使用webpack对前端代码进行模块化打包. 但是乍一看webpack ...

  8. 练手项目:利用pygame库编写射击游戏

    本项目使用pygame模块编写了射击游戏,目的在于训练自己的Python基本功.了解中小型程序框架以及学习代码重构等.游戏具有一定的可玩性,感兴趣的可以试一下. 项目说明:出自<Python编程 ...

  9. 适合Python的5大练手项目, 你练了么?

    在练手项目的选择上,还存在疑问?不知道要从哪种项目先下手? 首先有两点建议: 最好不要写太应用的程序练手,要思考什么更像是知识,老只会写写爬虫是无用的,但是完全不写也不行. 对于练手的程序,要注意简化 ...

随机推荐

  1. Spring Boot开发Web应用之JSP篇

    前言 上一篇介绍了Spring Boot中使用Thymeleaf模板引擎,今天来介绍一下如何使用SpringBoot官方不推荐的jsp,虽然难度有点大,但是玩起来还是蛮有意思的. 正文 先来看看整体的 ...

  2. SLC cache功能

    由于TLC需要多次编程,且未全部编程时wordLine处于不稳定状态,所以一般都会划出一部分区域作为SLC cache使用 SLC cache主要功能是,SSD接收到写命令后,先将数据写入SLC ca ...

  3. 说说mysql的存储引擎,有什么区别?索引的介绍

    InnoDB 支持ACID事务,支持事务的四种隔离级别,串行化,可重复读,读已提交,读未提交. 支持行级锁以及外检约束:所以可以支持写并发. 不存储总行数. 逐渐索引采用聚集索引,索引的数据域存储数据 ...

  4. centos 自动挂载ISO

    创建挂载点并挂载光盘mkdir -p /media/cdrommount -t iso9660 -o loop /usr/ison/centos.iso /media/cdrom 设置开机自动挂载:方 ...

  5. 架构模式:API组合

    架构模式: API组合 上下文 您已应用微服务架构模式和每服务数据库模式.因此,实现从多个服务连接数据的查询不再是直截了当的. 问题 如何在微服务架构中实现查询? 结论 通过定义API Compose ...

  6. 【052-week 预习周】学习总结

    目录 学习手册 学习理念 学员精选 课前准备 概览 数据结构思维导图 算法思维导图 学习手册 学习理念 让优秀的人一起学习 师傅领进门,修行靠个人 学员精选 稻盛和夫"六项精进" ...

  7. [Comet OJ - Contest #7 D][52D 2417]机器学习题_斜率优化dp

    机器学习题 题目大意: 数据范围: 题解: 学长说是决策单调性? 直接斜率优化就好了嘛 首先发现的是,$A$和$B$的值必定是某两个$x$值. 那么我们就把,$y$的正负分成两个序列,$val1_i$ ...

  8. SQL 拼接字符串 使用IN查询方法

    问题描述 当在 SQL SERVER 中查询的时候,同事遇到一个字段存储的字符串为用逗号分隔的主键 ID 值,格式为:1,2,3,4,这时候需要查询符合条件的所有数据,所以选择使用 IN 查询,但是直 ...

  9. Jenkins+SVN持续环境搭建

    需要三台不同环境的服务器,SVN.Jenkins.Tomcat 1.SVN搭建 1.Subversion服务器(SVN服务器) 2.项目对应的版本库 3.版本库中钩子程序(用于触发构建命令) 在我以前 ...

  10. one:arguments对象伪数组

    这是我的第一个博客 <script> //计算N个数字的和 //定义一个函数,如果不确定用户是否传入了参数,或者说不知道用户传入了几个参数,没办法计算, // 但是如果在函数中知道了参数的 ...