6

.Net Core微服务——网关(1):ocelot集成及介绍

 2 years ago
source link: https://www.cnblogs.com/muchengqingxin/p/15516270.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

网关是什么

简单来说,网关就是暴露给外部的请求入口。就和门卫一样,外面的人想要进来,必须要经过门卫。当然,网关并不一定是必须的,后端服务通过http也可以很好的向客户端提供服务。但是对于业务复杂、规模庞大的项目来说,使用网关有很多无法舍弃的好处,比如可以进行统一的请求聚合来节省流量、降低耦合度,可以赋予项目熔断限流的能力提高可用性等等。

ocelot是什么

ocelot是.net core实现的开源的api网关项目,开源地址:https://github.com/ThreeMammals/Ocelot

ocelot除了十分契合.net开发者以外,功能强大,包含:路由、认证、请求聚合、限流熔断、服务发现、鉴权,还有内置负载均衡器、Consul集成等等。

当然了,api网关不止这一款,市面上还有kong之类的,随自己喜好就好。

ocelot集成

首先明确一点,网关应该作为独立进程存在。那么我们先新建一个.net core3.1项目,然后添加nuget包:

关于版本,选择当前所能支持的最新版即可。

添加好nuget包以后,需要修改StartUp:

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();
            //services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseOcelot().Wait();

            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}

            //app.UseHttpsRedirection();

            //app.UseRouting();

            //app.UseAuthorization();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});
        }

这里不要惊讶,因为走了网关就不会再走默认的管道了。UseOcelot().Wait() 表示设置ocelot所有的中间件,而ocelot也提供了很多集成中间件的库,就像这些:

现在,想要让ocelot成功运行,还需要新增配置文件,并在Program新增配置文件的引用:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config =>
                {
                    config.AddJsonFile("ocelotConfig.json", optional: false, reloadOnChange: true);
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

配置文件:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/{url}", //服务地址--url变量
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "123.123.123.123",
          "Port": 5050 //服务端口
        }
      ],
      "UpstreamPathTemplate": "/MJ/{url}", //网关地址--url变量
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]
}

这是一份简单的转发配置,Downstream和Upstream开头的配置项就是下游、上游相关项。这里要说一句,在微服务架构中,客户端——服务端通常理解为上游——下游,这里自行替换一下。

上面的配置文件做了一件事,接收上游请求时,把请求路径中含有【/MJ/所有】的请求转发到IP【http://123.123.123.123:5050/所有】并回传结果,支持http的get、post方法,其实这就是最基本的路由。

来测试一下,启动项目并写好请求路径:

可以看到,ocelot成功把本地请求按照路由规则转发给远程服务器,并回发了结果。一个网关最基本的功能有了。

截图中所请求的远程服务,是我前几篇文章基于consul搭建起来的项目,有兴趣可以去看看。

关于ocelot更高级的应用,比如熔断限流、身份认证等,都是通过配置来完成的,我会整理后发出来,同时也建议仔细阅读官方文档,地址:https://ocelot.readthedocs.io/en/latest/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK