Ocelot 网关搭建(一)

一:环境配置

依赖项目:.Net Core 2.0 空项目

下载NuGet包:Install-Package Ocelot

二:相关代码与其他配置

添加应用设置文件:Ocelot.json

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8081
        }
      ],
      "UpstreamPathTemplate": "/Test/{url}",
      //负载均衡
      "LoadBalancer": "LeastConnection", //将请求发往最空闲的那个服务器  RoundRobin(轮流发送)、NoLoadBalance(总是发往第一个请求或者是服务发现)
      "UpstreamHttpMethod": [ "Get", "Post", "Delete" ],
      //限流
      "RateLimitOptions": {
        "ClientWhitelist": [], //白名单
        "EnableRateLimiting": true, //是否启用限流
        "Period": "1s", //统计时间段  1s, 5m, 1h, 1d
        "PeriodTimespan": 1, //多少秒之后客户端可以重试
        "Limit": 1 //在统计时间段内允许的最大请求数量
      },
      //服务质量与熔断
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, //允许多少个异常请求
        "DurationOfBreak": 5, //熔断的时间,单位为秒
        "TimeoutValue": 5000 //如果下游请求的处理时间超过多少则自如将请求设置为超时
      }
      //"AuthenticationOptions": {
      //  "AuthenticationProviderKey": "OcelotKey",
      //  "AllowedScopes": []
      //}
    },
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8082
        }
      ],
      "UpstreamPathTemplate": "/Test2/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]

}

将配置文件加入ASP.NET Core Configuration

Program.cs:

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

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

配置依赖注入与中间件

Startup.cs文件中:

引用:

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

添加:

public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("Ocelot.json", false, true)
               .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }


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

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

搭建完成~

备注:Ocelot.json配置中localhost:8081,localhost:8082为测试webApi项目

测试:(网关项目)localhost:8083/Test/api/Values  

Ocelot网关详细教程参考文章:https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值