当前位置: 移动技术网 > IT编程>开发语言>.net > Ocelot - .Net Core开源网关

Ocelot - .Net Core开源网关

2019年05月14日  | 移动技术网IT编程  | 我要评论

ocelot - .net core开源网关

作者:markjiang7m2
原文地址:
源码地址:https://gitee.com/sevenm2/ocelotdemo

今天要给大家介绍的ocelot是一个基于 .net core的开源webapi服务网关项目,它的功能非常强大,包括了路由、请求聚合、服务发现、认证鉴权、限流、负载均衡等功能。而这些功能都可以直接通过修改json配置文件即可使用,非常方便。ocelot是系统中对外暴露的一个请求入口,所有外部接口都必须通过这个网关才能向下游api发出请求,就如地铁中的安检系统,所有人都必须经过安检才能乘坐地铁。

我将通过具体案例对ocelot的功能进行一一展开说明,而本文中涉及案例的完整代码都可以从我的代码仓库进行下载。

搭建ocelot项目

通过vs2017新建一个基于 .net core webapi项目,然后通过nuget直接搜索ocelot或者使用以下命令行添加ocelot的引用。

install-package ocelot

在项目的根目录添加一个.json配置文件,文件名自定义,此案例为ocelot.json.添加配置如下:

{
    "reroutes": [],
    "globalconfiguration": {
    }
}

可以看到在我们的配置文件中包含两个配置项,reroutes是一个数组,将会包含服务器的路由配置,globalconfiguration则是一个全局配置项。我会在下文中通过各种案例详细说明配置项中的具体内容以及如何使用,因此,在这里暂时不展开说明。
将该配置文件添加到 .net core configuration中
program.cs

public static iwebhostbuilder createwebhostbuilder(string[] args) =>
    webhost.createdefaultbuilder(args)
        .configureappconfiguration((hostingcontext, builder) => {
            builder.addjsonfile("ocelot.json");
        })
        .usestartup<startup>();

因为 .net core支持当配置文件被修改后会重新加载,所以如果我们需要支持重新加载,可修改为:

public static iwebhostbuilder createwebhostbuilder(string[] args) =>
    webhost.createdefaultbuilder(args)
        .configureappconfiguration((hostingcontext, builder) => {
            builder.addjsonfile("ocelot.json", optional: false, reloadonchange: true);
        })
        .usestartup<startup>();

将ocelot作为中间件注册,需要添加两个命名空间
startup.cs

using ocelot.dependencyinjection;
using ocelot.middleware;
public void configureservices(iservicecollection services)
{
    services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
    services.addocelot();
}

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
    if (env.isdevelopment())
    {
        app.usedeveloperexceptionpage();
    }

    app.usemvc();
    app.useocelot().wait();
}

至此,我们的ocelot就已经搭建完成了。下面我们通过具体案例来说明如何修改配置进行相关功能的使用。

配置参数介绍

我们先来认识一下到底包含哪些参数,以及这些参数的含义。前面我们有介绍到,配置文件中包含两个配置项:reroutes和globalconfiguration。
我们先来看globalconfiguration,它是一个全局配置项,通常我们都要在这个配置项中添加一个属性baseurl,baseurl就是ocelot服务对外暴露的url。

"globalconfiguration": {
    "baseurl": "http://localhost:4727"
}

reroutes是一个数组,其中的每一个元素代表了一个路由,而一个路由所包含的所有可配置参数如下:

{
    "downstreampathtemplate": "/",
    "upstreampathtemplate": "/",
    "upstreamhttpmethod": [
        "get"
    ],
    "addheaderstorequest": {},
    "addclaimstorequest": {},
    "routeclaimsrequirement": {},
    "addqueriestorequest": {},
    "requestidkey": "",
    "filecacheoptions": {
        "ttlseconds": 0,
        "region": ""
    },
    "rerouteiscasesensitive": false,
    "servicename": "",
    "downstreamscheme": "http",
    "downstreamhostandports": [
        {
            "host": "localhost",
            "port": 8001,
        }
    ],
    "qosoptions": {
        "exceptionsallowedbeforebreaking": 0,
        "durationofbreak": 0,
        "timeoutvalue": 0
    },
    "loadbalancer": "",
    "ratelimitoptions": {
        "clientwhitelist": [],
        "enableratelimiting": false,
        "period": "",
        "periodtimespan": 0,
        "limit": 0
    },
    "authenticationoptions": {
        "authenticationproviderkey": "",
        "allowedscopes": []
    },
    "httphandleroptions": {
        "allowautoredirect": true,
        "usecookiecontainer": true,
        "usetracing": true
    },
    "useservicediscovery": false
}
  • downstream 下游服务配置
  • upstream 上游服务配置
  • aggregates 服务聚合配置
  • servicename, loadbalancer, useservicediscovery 服务发现配置
  • authenticationoptions 服务认证配置
  • routeclaimsrequirement claims 鉴权配置
  • ratelimitoptions 限流配置
  • filecacheoptions 缓存配置
  • qosoptions 服务质量与熔断配置
  • downstreamheadertransform 头信息转发配置

当然,我们在实际使用过程中不需要设置所有的参数,只需要根据实际需要进行配置即可。

案例一 路由

路由是ocelot最基本的功能。ocelot接收到来自上游服务的请求,经过验证后,将请求转发到下游服务,因此,我们首先要配置路由当中上下游服务参数。

{
    "downstreampathtemplate": "/api/ocelot/{id}",
    "downstreamscheme": "http",
    "downstreamhostandports": [
            {
                "host": "localhost",
                "port": 8001,
            }
        ],
    "upstreampathtemplate": "/ocelot/{id}",
    "upstreamhttpmethod": ["get"]
}
  • downstreampathtemplate 下游请求url模板,{}中的内容代表动态参数
  • downstreamscheme 下游服务http scheme
  • downstreamhostandports 下游服务的地址,如果使用loadbalancer的话这里可以填多项
  • upstreampathtemplate 上游也就是用户输入的请求url模板
  • upstreamhttpmethod 上游请求http方法,可使用数组

因此,当上游服务向地址http://localhost:4727/ocelot/5发出请求时,ocelot会将请求转发到下游服务http://localhost:8001/api/ocelot/5
本案例提供了下游服务demo - ocelotdownapi,将ocelotdownapi发布到iis端口即可使用。下游服务在接收到请求后返回一个字符串用于表明自己的身份。

[httpget("{id}")]
public async task<iactionresult> get(int id)
{
    var result = await task.run(() =>
    {
        return $"this is from {httpcontext.request.host.value}, path: {httpcontext.request.path}";
    });
    return ok(result);
}

测试结果:
ocelot_001_routing1.png

如果希望ocelot能够转发所有的请求,则可以配置如下:

{
    "downstreampathtemplate": "/{url}",
    "downstreamscheme": "http",
    "downstreamhostandports": [
            {
                "host": "localhost",
                "port": 8001,
            }
        ],
    "upstreampathtemplate": "/{url}",
    "upstreamhttpmethod": ["get"]
}

这样就能将所有get请求转发到下游服务。不过这样配置的优先级是最低的,一旦匹配到其它路由模板,会优先选择。

如果希望ocelot只转发来自某个特定上游服务host的请求,则可以配置如下:

{
    "downstreampathtemplate": "/{url}",
    "downstreamscheme": "http",
    "downstreamhostandports": [
            {
                "host": "localhost",
                "port": 8001,
            }
        ],
    "upstreampathtemplate": "/{url}",
    "upstreamhttpmethod": ["get"],
    "upstreamhost": "localhost:4023"
}

这样ocelot就只会转发来自localhost:4023的请求。需要注意的是,如果路由配置中包含两个除upstreamhost以外都相同的路由,即其中一个带有upstreamhost,而另外一个没有,则ocelot会优先选择带有upstreamhost的路由。

设置路由的优先级。我们可以定义reroutes路由数组中响应的优先级。0是最低的优先级,数字越大,优先级越高。

[
{
    "upstreampathtemplate": "/ocelot/{id}"
    "priority": 0
},
{
    "upstreampathtemplate": "/ocelot/10"
    "priority": 1
},
]

总结

本文主要介绍了ocelot的功能,并通过简单的案例讲述如何构建ocelot网关以及对ocelot的基本应用。由于ocelot功能非常的强大,如果将所有的案例都放到同一篇文章中会导致篇幅过长,不便于阅读,因此,我将会针对ocelot功能写成系列文章,希望大家继续捧场。

参考文献
本文在编写过程中引用或参考了以下文章中的部分内容,如有侵权,请联系修改或删除。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网