1. 程式人生 > >.NET Core 玩一玩 Ocelot API網關

.NET Core 玩一玩 Ocelot API網關

gin 配置服務 exceptio gen .config services local lec new

.net 這幾年國內確實不好過。 很多都選擇轉行。不過.net Core跨平臺 開源之後 。社區的生態在慢慢建立。往好的趨勢發展。 對於堅守在.NET戰線的開發者來說 是個挺不錯的消息。

特別是微軟收購75億美金GitHub。.net 生態 社區圈子。肯定會有所上升。 發展趨勢越來越好。(當然 這只是我個人祈願)

最近也比較懶。也有段時間沒有寫過文章了。 但對於追尋新技術渴望學習 是不會斷的

最近微服務比較火熱。 將以個大型項目根據業務可以拆分成一個個的較小的獨立項目。便於管理 且互相協作

什麽是Ocelot

Ocelot是一個用.NET Core實現並且開源的API網關,它功能強大,包括了:路由、請求聚合、服務發現、認證、鑒權、限流熔斷、並內置了負載均衡器與Service Fabric、Butterfly Tracing集成。這些功能只都只需要簡單的配置即可完成

但是現在網上關於Ocelot的文章還是有限。

首先感謝幾位大佬 Ocelot的文章

https://www.cnblogs.com/shanyou/p/7787183.html(張友善 大神)

https://www.cnblogs.com/Leo_wl/p/7852311.html (HackerVirus 大神)

https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html(騰飛(Jesse) 大神)

首先用VS2017 新建一個 .NET Core Api

技術分享圖片

1.NuGet控制臺 安裝Ocelot

PM> Install-Package Ocelot

2.在項目 Startup.cs 修改

這裏需要用到兩個比較重要的命名空間

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

 public Startup(IHostingEnvironment environment)
        {
            var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
            builder.SetBasePath(environment.ContentRootPath)
                   .AddJsonFile(
"appsettings.json", false, reloadOnChange: true) .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: false, reloadOnChange: true) .AddJsonFile("configuration.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); }

 /// <summary>
        ///配置
        /// </summary>
        public IConfigurationRoot Configuration { get; }

        /// <summary>
        /// 配置服務
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            Action<ConfigurationBuilderCachePart> settings = (x) =>
            {
                x.WithMicrosoftLogging(log =>
                {
                    log.AddConsole(LogLevel.Debug);

                }).WithDictionaryHandle();
            };
            services.AddOcelot(Configuration, settings);
            //services.AddMvc();
        }

 /// <summary>
        /// 配置Ocelot
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            await app.UseOcelot();
            //app.UseMvc();
        }

然後是入口程序Main

       public static void Main(string[] args)
        {
            IWebHostBuilder builder = new WebHostBuilder();
            builder.ConfigureServices(s =>
            {
                s.AddSingleton(builder);
            });
            builder.UseKestrel()
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .UseIISIntegration()
                   .UseStartup<Startup>()
                   .UseApplicationInsights();
            var host = builder.Build();
            host.Run();
        }

3. 新建一個命名為configuration的Json 文件

技術分享圖片

增加配置 如下

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/values",
      "DownstreamScheme": "http",
      "DownstreamHost": "localhost",
      "DownstreamPort": 1001,
      "UpstreamPathTemplate": "/api/values",
      "UpstreamHttpMethod": [ "Get" ],
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3,
        "DurationOfBreak": 10,
        "TimeoutValue": 5000
      },
      "HttpHandlerOptions": {
        "AllowAutoRedirect": false,
        "UseCookieContainer": false
      },
      "AuthenticationOptions": {

      }
    },
    {
      "DownstreamPathTemplate": "/api/product",
      "DownstreamScheme": "http",
      "DownstreamPort": 1002,
      "DownstreamHost": "localhost",
      "UpstreamPathTemplate": "/api/product",
      "UpstreamHttpMethod": [ "Get" ],
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3,
        "DurationOfBreak": 10,
        "TimeoutValue": 5000
      },
      "AuthenticationOptions": {

      }
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/admin"
  }
}

然後新建兩個APi項目

技術分享圖片

並設置他們端口號為1001 1002

技術分享圖片

另一個類似

上面Json配置體現了上遊請求和下遊服務間的映射關系 上遊是客戶端直接調用的URL ,下遊,則是對應我們開發的服務。

然後 你可以設置多項目啟動 也可以單獨開啟新實例

技術分享圖片

接下 F5啟動項目

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

最後附上Ocelot在GitHub上源碼地址

https://github.com/TomPallister/Ocelot

.NET Core 玩一玩 Ocelot API網關