net core 中Ocelot webapi getway入門實踐(一)

1.Ocelot介紹

Ocelot是一個.net core框架下的網關的開源項目,下圖是官方給出的基礎實現圖,即把後臺的多個服務統一到網關處,前端應用:桌面端,web端,app端都只用訪問網關即可,如下圖:

Ocelot是一個.net core框架下的網關的開源項目,下圖是官方給出的基礎實現圖

關於Ocelot的詳細使用說明,可以到官網查看:https://ocelot.readthedocs.io/en/latest/

2.項目搭建

項目使用的visual studio 2017,net core版本是2.2
新建三個net core webapi項目,如下:
JuCheap.OcelotApiGetWay (網關webapi項目),地址:http://localhost:44773
JuCheap.Order (訂單系統webapi項目),地址:http://localhost:46237
JuCheap.Product (產品系統webapi項目),地址:http://localhost:46254

api項目的端口可以自己配置,但是需要注意,配置後,需要在ocelot.json文件中,做對應的修改。效果如下圖:

ocelot網關項目解決方案 jucheap

3.網關項目配置

在JuCheap.OcelotApiGetWay中引入Ocelot的包,包含OcelotOcelot.Provider.ConsulOcelot.Provider.Polly,如下圖:

jucheap ocelot 網關

新建ocelot.json配置文件,配置文件裏面,我們只需要關心如下配置節點:

DownstreamPathTemplate 上游轉發到下游的url地址(也就是我們的目標api的地址,比如產品系統的api或者訂單系統的api)

UpstreamPathTemplate 上游api路由模板地址

UpstreamHttpMethod 上游支持的請求方式

DownstreamScheme 下游的http頭

DownstreamHostAndPorts.Host 下游的api Host

DownstreamHostAndPorts.Port 下游的api端口

ocelot.json的完整代碼如下:

{
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/admin"
  },
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{url}",
      "UpstreamPathTemplate": "/order/{url}",
      "UpstreamHttpMethod": [
        "Get"
      ],
      "AddHeadersToRequest": {},
      "AddClaimsToRequest": {},
      "RouteClaimsRequirement": {},
      "AddQueriesToRequest": {},
      "RequestIdKey": "",
      "FileCacheOptions": {
        "TtlSeconds": 0,
        "Region": ""
      },
      "ReRouteIsCaseSensitive": false,
      "ServiceName": "",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 46237
        }
      ],
      "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
      },
      "DangerousAcceptAnyServerCertificateValidator": false
    },
    {
      "DownstreamPathTemplate": "/{url}",
      "UpstreamPathTemplate": "/product/{url}",
      "UpstreamHttpMethod": [
        "Get"
      ],
      "AddHeadersToRequest": {},
      "AddClaimsToRequest": {},
      "RouteClaimsRequirement": {},
      "AddQueriesToRequest": {},
      "RequestIdKey": "",
      "FileCacheOptions": {
        "TtlSeconds": 0,
        "Region": ""
      },
      "ReRouteIsCaseSensitive": false,
      "ServiceName": "",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 46254
        }
      ],
      "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
      },
      "DangerousAcceptAnyServerCertificateValidator": false
    }
  ]
}

然後將配置文件加入到WebHostBuilder中,找到Program.cs文件的Main方法,如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Ocelot.Middleware;
using Ocelot.DependencyInjection;

namespace JuCheap.OcelotApiGetWay
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config
                        .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                        .AddJsonFile("appsettings.json", true, true)
                        .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                        .AddJsonFile("ocelot.json")
                        .AddEnvironmentVariables();
                })
                .Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

在Startup.cs文件中,配置Ocelot的服務,在ConfigureServices方法裏面新增如下代碼:

services.AddOcelot(Configuration).AddConsul().AddPolly();

並在Configure方法裏面啓用Ocelot網關服務,代碼如下:

app.UseOcelot().Wait();

Startup.cs完整代碼如下: 

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;

namespace JuCheap.OcelotApiGetWay
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

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

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseOcelot().Wait();

            //app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

最後將我們的3個api都配置成啓動項目,右鍵點擊解決方案,然後找到"屬性"->"啓動項目",選擇多個啓動項目欄,把要啓動的項目的操作一欄,改成“啓動”,如下圖:
 

vs多項目啓動 jucheap

到此,我們就可以啓動項目了,點擊菜單欄上的“啓動”,我們訪問網關項目的如下地址:
http://localhost:44773/order/api/order
http://localhost:44773/product/api/p
roduct

效果如下圖:

項目源代碼:

https://github.com/jucheap/JuCheap.Ocelot

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章