netty实现http服务器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zzti_erlie/article/details/81607450

前言

因为项目需要,就写了一下,当然为了写的更好还是参考了很多GitHub和码云上的开源代码,各有利弊,这里就简单写一个我的心得

我的项目 GitHub地址:https://github.com/erlieStar/study_nio

开源代码

netty-restful-server

项目地址:https://github.com/zhoumengkang/netty-restful-server
可以到我的GitHub上clone一份注释版:https://github.com/erlieStar/netty-restful-server
这个项目比较精简,Star也最多,很快就能理清项目的整体思路

ApiRoute是一个配置类,定义了Url路径和对应的Controller之间的映射关系,配置信息在routeMap.xml这个配置文件中,每个映射关系又是一个Api类

<?xml version="1.0" encoding="UTF-8"?>
<routeMap>
    <api>
        <name>/user</name>
        <method>post</method>
        <resource>UserResource</resource>
    </api>
    <api>
        <name>/user/:uid</name>
        <method>get</method>
        <method>patch</method>
        <method>delete</method>
        <resource>UserResource</resource>
        <build>101</build>
    </api>
</routeMap>

Api类的属性,和上面的XML文件中的属性差不多,name属性匹配url路径,method是支持的http方法,resource是指定哪个类来执行,build是服务的版本

public class Api {

    private String       name;  // endpoint
    private String       regex;
    private List<String> parameterNames;
    private Set<String>  httpMethod;
    private String       resource;
    private int          build;
}

ApiProtocol

  1. 解析出访问的url
  2. 获取路径中的参数并放到parameters中
  3. 设置客户端ip和服务端ip
  4. 对url进行decode(解码)
  5. 如果是post请求获取post请求的值
  6. 将parameters中有的参数设置到ApiProtocol这个对象中,并从parameters中移除

执行过程
1.ApiHandler的transfer为处理的入口

FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(ApiHandler.transfer(ctx,msg)));

在这个方法中会初始化ApiProtocol这个类,这个类的主要作用上面已经说明

2.ApiHandler的invoke为具体的执行过程,这里对每个请求都会反射生成相应的类,每个Service类必须继承BaseService,这样就用用统一的ApiProtocol这个类来构造Service,根据请求的http方法调用响应的Service方法,如http是get请求则调用Service的get方法,如果是post请求则调用Service的post方法

ditty

项目地址:https://gitee.com/dingnate/ditty/tree/master/src/main/java/com/ditty

loServer

项目地址:https://gitee.com/loolly/loServer

扫描二维码关注公众号,回复: 2965821 查看本文章

light

项目地址:https://gitee.com/liyongyao/light

参考博客

[1]https://blog.csdn.net/huangshanchun/article/details/78302602

猜你喜欢

转载自blog.csdn.net/zzti_erlie/article/details/81607450