.netcore的微服务学习(四)--网关(gateway)之Ocelot+Consul+polly学习

一,接着前面的代码,我们先引用Ocelot.Provider.Polly,然后我们的startup接着配置下,如下

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.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;

namespace OcelotDemo
{
    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().AddConsul().AddPolly();
        }

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

二,Polly之缓存设置,如下配置(缓存:就是在网关缓存请求的值,时间也是在配置中设置,本配置设置的是10S,这个适用于一般不会变化的值)

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/TestOcelotConsul/{url}", //网关地址--url变量
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "ServiceName": "TestConsulService", //consul服务名称
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //轮询      LeastConnection-最少连接数的服务器   NoLoadBalance不负载均衡
      },
      "UseServiceDiscovery": true,
      "FileCacheOptions": {
        "TtlSeconds": 10  //在第一次请求在网关缓存10,在十秒内怎么请求都是都网关的缓存,不会请求实例,降低压力,提升性能
      } //"缓存"
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://127.0.0.1:5003", //网关对外地址
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500,
      "Type": "Consul" //由Consul提供服务发现
    }
  }
}

1》这个时候我们一直请求http://localhost:5003/TestOcelotConsul/user/get配置的网关地址,发现返回的都是5001接口的值,而在第10s后才会出现第二个实例的值,这个就是接口缓存,这个缓存是网关的缓存,这个减少实例的压力,提升性能

三,Polly之限流设置,如下配置(限流:就是在设定的时间内,允许请求的次数,如果达到次数,就返回设定的信息)

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/TestOcelotConsul/{url}", //网关地址--url变量
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "ServiceName": "TestConsulService", //consul服务名称
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //轮询      LeastConnection-最少连接数的服务器   NoLoadBalance不负载均衡
      },
      "UseServiceDiscovery": true,
      "RateLimitOptions": {    //限流,限制了单位时间内的访问量
        "ClientWhitelist": [], //白名单
        "EnableRateLimiting": true,
        "Period": "5m", //1s, 5m, 1h, 1d  
        "PeriodTimespan": 5, //多少秒之后客户端可以重试
        "Limit": 5 //统计时间段内允许的最大请求数量
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://127.0.0.1:5003", //网关对外地址
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500,
      "Type": "Consul" //由Consul提供服务发现
    },
    "RateLimitOptions": {
      "QuotaExceededMessage": "Too many requests!!!!!!!", // 当请求过载被截断时返回的消息,中文会出现乱码
      "HttpStatusCode": 503 // 当请求过载被截断时返回的http status,经测试过超过4位的状态码会出现异常
    }
  }
}

1》我们请求6次这个网关地址http://localhost:5003/TestOcelotConsul/user/get,就会出现我们配置的返回信息,这里设置逻辑是五分钟内访问五次,第六次提示限流,在第七次我们又可以访问,这个意思不是五分钟内一种只能访问五次

我们注意RateLimitOptions这个设置的值,中文和状态码的长度

 四,Polly之熔断设置,如下配置(熔断:单位时间内超时,我们就直接停掉该请求返回)

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/TestOcelotConsul/{url}", //网关地址--url变量
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "ServiceName": "TestConsulService", //consul服务名称
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //轮询      LeastConnection-最少连接数的服务器   NoLoadBalance不负载均衡
      },
      "UseServiceDiscovery": true,
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, //允许多少个异常请求
        "DurationOfBreak": 4000, // 熔断的时间,单位为ms
        "TimeoutValue": 5000 //如果下游请求的处理时间超过多少则自如将请求设置为超时 默认90秒
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://127.0.0.1:5003", //网关对外地址
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500,
      "Type": "Consul" //由Consul提供服务发现
    }
  }
}

我们在UserController添加一个超时的请求10000s的方法GetTimeOut

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace ConsulTestDemo.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        public IConfiguration _configuration;
        public UserController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet]
        public string Get()
        {
            return int.Parse(_configuration["port"]).ToString() + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //命令行参数必须传入   
        }
        private static int _count = 0;
        [HttpGet]
        public string GetTimeOut()
        {
            if (int.Parse(_configuration["port"]).ToString() == "5001")
            {
                _count++;
                Console.WriteLine($"Get...{_count}");
                if (_count <= 10)
                {
                    ///这里休眠10000s实际上熔断机制根据配置的设置,请求超时4秒就返回
                    System.Threading.Thread.Sleep(10000000);
                }
                ///测试在请求十次后系统修复了,又可以正常访问
                return int.Parse(_configuration["port"]).ToString() + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                return int.Parse(_configuration["port"]).ToString() + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //命令行参数必须传入   
            }
        }
    }
}

现在我们正常启动服务和网关(看前几篇博客启动命令),访问http://localhost:5003/TestOcelotConsul/user/GetTimeout网关,这个时候我们设置如果超过4s就熔断,看我们的请求,达到四秒超时的时候直接返回了,如下图,

我们看看正常的请求,一直在延时请求,

 

这个就是熔断的区别,可以设置请求超时熔断,避免一直占用进程,慢查询,然后导致服务器崩溃

原文地址:https://www.cnblogs.com/May-day/p/13375211.html