微服務(入門三):netcore ocelot api網關結合consul服務發現


簡介

  api網關是提供給外部調用的統一入口,類似於dns,所有的請求統一先到api網關,由api網關進行指定內網鏈接。

  ocelot是基於netcore開發的開源API網關項目,功能強大,使用方便,它包含了負載均衡、路由、請求聚合、服務發現、權限認證等功能。

基礎准備

  開發環境:vs2017

  netcore:2.1

新建項目

  

 

 

netcore安裝ocelot

  • install-package Ocelot  安裝ocelot組件

配置ocelot

 1.添加ocelotSettings.json文件,並且在program.cs文件當中添加配置信息

 

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;

namespace ocelotTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
         WebHost.CreateDefaultBuilder(args)
             .UseStartup<Startup>()
            .UseUrls("http://localhost:8683")
         .ConfigureAppConfiguration(conf => {
             conf.AddJsonFile("OcelotSettings.json", optional: false, reloadOnChange: true);
         })
             .Build();
    }
}

2.注入ocelot服務

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;

namespace ocelotTest
{
    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)
        {
            //注入ocelot服務
            services.AddOcelot(Configuration).AddConsul().AddPolly();
        }

        // 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();
            }

            app.UseOcelot().Wait();
        }
    }
}

3.配置ocelotSettings.json

{
  "ReRoutes": [

    {
      //下游路由模板,真實請求的路徑
      "DownstreamPathTemplate": "/api/{everything}",
      //請求的方式,例如:http,https
      "DownstreamScheme": "http",
      //服務器名稱
      "ServiceName": "zyz",
      //啟用consul服務
      "UseServiceDiscovery": true,
      //服務熔斷
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, //允許多少次異常請求
        "DurationOfBreak": 5, //熔斷時間,單位為秒
        "TimeoutValue": 5000 //如果下游請求的處理時間超過多少則自動設置超時
      },
      "HttpHandlerOptions": {
        "AllowAutoRedirect": false,
        "UseCookieContainer": false,
        "UseTracing": false
      },
      "ReRouteIsCaseSensitive": false,
      //負載均衡:
      //RoundRobin輪流發送;
      //LeastConnection – 將請求發往最空閑的那個服務器
      //NoLoadBalance – 總是發往第一個請求或者是服務發現
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      },
      //上游地址配置
      "UpstreamPathTemplate": "/test/{everything}",
      //上游支持的請求類型
      "UpstreamHttpMethod": [ "Post", "Get" ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:8683",
    //consul服務器地址和ip
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500
    }
  }
}

4.啟動ocelot項目和consul服務。

把服務注冊到consul當中,通過postman發送請求測試,成功轉發消息,並且實現負載均衡。

 

 

小結:簡單的ocelot搭建完成,后續的一些擴展功能慢慢在研究。

 

快速入口:微服務(入門一):netcore安裝部署consul

快速入口: 微服務(入門二):netcore通過consul注冊服務

快速入口: 微服務(入門三):netcore ocelot api網關結合consul服務發現

快速入口:微服務(入門四):identityServer的簡單使用(客戶端授權) 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM