netty实现http服务器

前言

因为项目需要,就写了一下,当然为了写的更好还是参考了很多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

light

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

参考博客

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java识堂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值