• 2022年11月2日

.net 6配置api网关ocelot

1、新建webapi项目

2、添加依赖

install-package ocelot
install-package ocelot.provider.consul

3、添加配置(配合Consul,安装Consul可参考《.Net6 Furion框架配置Consul》

ocelot.json
{
  "Routes": [
    {
      "UpstreamPathTemplate": "/user/{url}",
      "UpstreamHttpMethod": [ "Get", "Post", "Put" ],

      "UseServiceDiscovery": true, //启用通过服务发现
      "ServiceName": "User", //Consul对应的Service Name

      "DownstreamPathTemplate": "/{url}",
      "DownstreamScheme": "http",
      //"DownstreamHostAndPorts": [
      //  { //如果关闭通过服务发现则需要配置此处
      //    "Host": "localhost",
      //    "Port": 5001
      //  }
      //],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //负载均衡方式
      }
      //缓存
      //"FileCacheOptions": {
      //  "TtlSeconds": 30, //缓存时间(秒)
      //  "Region": "CacheArea" //缓存区(名称自定义),表示改配置缓存放到哪个区域,可以在配置管理中进行维护
      //}
    } 
  ],
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "127.0.0.1", //Consul客户端的IP
      "Port": 8500,
      "Type": "Consul" //PollConsul
    },
    "BaseUrl": "https://api.yourname.com", //对外的网关网址
    "RateLimitOptions": {
      "QuotaExceededMessage": "Too many requests, maybe later? ", // 当请求过载被截断时返回的消息
      "HttpStatusCode": 666, // 当请求过载被截断时返回的http status
      "ClientIdHeader": "client_id" // 用来识别客户端的请求头,默认是 ClientId
    }
  }
}

4、Startup.cs配置

 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.AddControllers();
            services.AddOcelot(new ConfigurationBuilder().AddJsonFile("ocelot.json").Build())
                .AddConsul(); 
            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseOcelot().Wait(); 

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

注意:

services.AddOcelot().AddConsul() 如果缺少紫色部分(需要安装对应的Provider,例如Ocelot.Provider.Consul),配置又启用了服务发现,就会出现如下错误:

Exception: Unable to start Ocelot, errors are: Unable to start Ocelot, errors are: Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?,Unable to start Ocelot, errors are: Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注