Ocelot + Consul的demo


參考大佬的博客寫的:https://www.cnblogs.com/alan-lin/p/9126155.html;也可以參考這篇博客:https://www.cnblogs.com/axzxs2001/p/8487521.html

首先下載Consulhttps://www.consul.io/downloads.html,本項目是windows下進行測試,然后把下載的添加到

的path中;這樣的話環境變量接配置好了

 

項目結構如下:

 

 

 加一個core的web空白項目TestApiGateway;在nuget中找到包ocelot;添加一個Ocelot.json的文件:

{
  //路由配置
  "ReRoutes": [
    {
      "UpstreamPathTemplate": "/apiservice/{controller}/{action}", //請求路徑模板
      "UpstreamHttpMethod": [ "Get", "POST" ], //請求方法數組
      "DownstreamPathTemplate": "/apiservice/{controller}/{action}", //下游請求地址模板
      "DownstreamScheme": "http", //請求協議,目前應該是支持http和https
      "DownstreamHostAndPorts": [ //下游地址和端口
        {
          "host": "localhost",
          "port": 5011
        },
        {
          "host": "localhost",
          "port": 5012
        }
      ],
      "LoadBalancerOptions": { //負載均衡 RoundRobin(輪詢)/LeastConnection(最少連接數)/CookieStickySessions(相同的Sessions或Cookie發往同一個地址)/NoLoadBalancer(不使用負載)
        "Type": "RoundRobin"
      }
    }
  ],

  "GlobalConfiguration": { //全局配置
    "BaseUrl": "http://localhost:5000" //告訴別人網關對外暴露的域名
  }
}

然后修改倆個類如下:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build()
                                      .Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, builder) => {
                builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
                .AddJsonFile("Ocelot.json");//testOcelot.json
            })
            .UseKestrel()
            .UseUrls("http://localhost:5000")
            .UseStartup<Startup>();
    }
public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot();
        }

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

            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
        }
    }

這個這個網關項目基本就配置完了

現在添加兩個api項目TestServiceA和TestServiceB,修改Startup的端口分別為5011和5012

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://localhost:5011")
                .UseStartup<Startup>();

這個是項目不是在debug啟動下的端口配置,還需要修改appsettings.json文件如下,是為了區分調用的api是哪個

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "AppName": "ServiceA"
}

 

然后是接口的類容,只留下get和post請求即可,這個接口的返回結果可以修改,

[Route("apiservice/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        public IConfiguration Configuration { get; }

        public ValuesController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1A", "value2A" };
        }

        // GET api/values/5
        [HttpGet]//("{id}")
        public ActionResult<string> Getid(int id)
        {
            return HttpContext.Request.Host.Port + "=>" + Configuration["AppName"] + "=>" + DateTime.Now.ToString() + "=>" + id;
        }

        // POST api/values
        [HttpPost]
        public string Post(string value)
        {
            return HttpContext.Request.Host.Port + "=>" + Configuration["AppName"] + "=>" + DateTime.Now.ToString() + "=>" + value;
        }

        [HttpGet]
        public IActionResult Heathle()
        {
            return Ok();
        }
    }

如果是要debug下啟動項目測試:右鍵項目屬性修改端口

 

 

 測試效果如下:

這個接口就找輪播了

添加 Consul的支持

 

 

 

conf 配置目錄

data 緩存數據目錄,可清空里面內容

dist Consul UI目錄

consul.exe 注冊軟件

startup.bat 執行腳本

 

修改配置文件service.json

 

{
  "encrypt": "7TnJPB4lKtjEcCWWjN6jSA==",
  "services": [
    {
      "id": "ApiServiceA",
      "name": "ApiServiceA",
      "tags": [ "ApiServiceA" ],
      "address": "localhost",
      "port": 5011,
      "checks": [
        {
          "id": "ApiServiceA_Check",
          "name": "ApiServiceA_Check",
          "http": "http://localhost:5011/apiservice/values/heathle",
          "interval": "10s",
          "tls_skip_verify": false,
          "method": "GET",
          "timeout": "1s"
        }
      ]
    },
    {
      "id": "API服務A",
      "name": "ApiServiceB",
      "tags": [ "ApiServiceB" ],
      "address": "localhost",
      "port": 5012,
      "checks": [
        {
          "id": "ApiServiceB_Check",
          "name": "ApiServiceB_Check",
          "http": "http://localhost:5012/apiservice/values/heathle",
          "interval": "10s",
          "tls_skip_verify": false,
          "method": "GET",
          "timeout": "1s"
        }
      ]
    }
  ]
}

 

修改startup.bat 腳本

consul agent -server -datacenter=dc1 -bootstrap -data-dir ./data -config-file ./conf -ui-dir ./dist -node=n1 -bind 127.0.0.1 -client=0.0.0.0

然后啟動api服務和startup.bat 腳本,效果如下

 

 最后這是在一個服務上的,要在多個服務商的參考:https://www.cnblogs.com/alan-lin/p/9126155.html,我也是按這個博客來寫的demo,然后記個筆記;哈哈哈

 

ocelot配置文件基本參數,具體參考官方文檔:https://ocelot.readthedocs.io/en/latest/index.html

{
  "ReRoutes": [ //路由是API網關最基本也是最核心的功能、ReRoutes下就是由多個路由節點組成。
    {
      "DownstreamPathTemplate": "", //下游服務模板
      "UpstreamPathTemplate": "", //上游服務模板
      "UpstreamHttpMethod": [ "Get" ],//上游方法類型Get,Post,Put
      "AddHeadersToRequest": {},//需要在轉發過程中添加到Header的內容
      "FileCacheOptions": { //可以對下游請求結果進行緩存,主要依賴於CacheManager實現
        "TtlSeconds": 10,
        "Region": ""
      },
      "ReRouteIsCaseSensitive": false,//重寫路由是否區分大小寫
      "ServiceName": "",//服務名稱
      "DownstreamScheme": "http",//下游服務schema:http, https
      "DownstreamHostAndPorts": [ //下游服務端口號和地址
        {
          "Host": "localhost",
          "Port": 8001
        }
      ],
      "RateLimitOptions": { //限流設置
        "ClientWhitelist": [], //客戶端白名單
        "EnableRateLimiting": true,//是否啟用限流設置
        "Period": "1s", //每次請求時間間隔
        "PeriodTimespan": 15,//恢復的時間間隔
        "Limit": 1 //請求數量
      },
      "QoSOptions": { //服務質量與熔斷,熔斷的意思是停止將請求轉發到下游服務。當下游服務已經出現故障的時候再請求也是無功而返,
      並且增加下游服務器和API網關的負擔,這個功能是用的Polly來實現的,我們只需要為路由做一些簡單配置即可
        "ExceptionsAllowedBeforeBreaking": 0, //允許多少個異常請求
        "DurationOfBreak": 0, //熔斷的時間,單位為秒
        "TimeoutValue": 0 //如果下游請求的處理時間超過多少則自如將請求設置為超時
      }
    }
  ],
  "UseServiceDiscovery": false,//是否啟用服務發現
  "Aggregates": [ //請求聚合
    {
      "ReRouteKeys": [ //設置需要聚合的路由key
        "booking",
        "passenger"
      ],
      "UpstreamPathTemplate": "/api/getbookingpassengerinfo" //暴露給外部的聚合請求路徑
    },
  "GlobalConfiguration": { //全局配置節點
    "BaseUrl": "https://localhost:5000" //網關基地址
  }
}

 

路由分開寫要注意,不然報錯

 限流和聚合,聚合只能get請求,返回json類型

{
  "ReRoutes": [ { "DownstreamPathTemplate": "/apiA/{controller}/{action}", //api地址 "UpstreamPathTemplate": "/api/{controller}/{action}", //請求輸入的地址 "UpstreamHttpMethod": [ "Get", "POST" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5011 } ] }, { "DownstreamPathTemplate": "/apiB/{controller}/{action}", "UpstreamPathTemplate": "/api2/{controller}/{action}", "UpstreamHttpMethod": [ "Get", "POST" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5012 } ] }, { "DownstreamPathTemplate": "/apiA/Values/Get", "UpstreamPathTemplate": "/api/getbooking", "UpstreamHttpMethod": [ "Get" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5011 } ], "Key": "booking", "RateLimitOptions": { //限流 "ClientWhitelist": [], "EnableRateLimiting": true, "Period": "1s", "PeriodTimespan": 15, "Limit": 1 } }, { "DownstreamPathTemplate": "/apiB/Values/Get", "UpstreamPathTemplate": "/api/getpassenger", "UpstreamHttpMethod": [ "Get" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5012 } ], "Key": "passenger" } ], "GlobalConfiguration": { "BaseUrl": "https://localhost:5010" }, "Aggregates": [ { "ReRouteKeys": [ //聚合的路由 "booking", "passenger" ], "UpstreamPathTemplate": "/api/getbookingpassengerinfo" //聚合請求地址 } ] }

限流請求超過次數結果

 聚合請求結果

 demo的地址:https://gitee.com/cainiaoA/ocelot_consuls_demo


免責聲明!

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



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