天天看點

Ocelot使用

1、在網關項目中通過nuget引入Ocelot

2、Startup.cs檔案代碼調整

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
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;

namespace ApiGateway
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            //通過nuget引入如下包
            //Microsoft.Extensions.Options.ConfigurationExtensions
            //Microsoft.Extensions.Configuration.Json

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("configuration.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json");

            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddOcelot(Configuration);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseOcelot();
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
           

3、添加網關支援配置configuration.json

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/order", /*下遊路徑模闆*/
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9001
        }
      ],
      "UpstreamPathTemplate": "/order", /*上遊路徑模闆*/
      "UpstreamHttpMethod": [ "Get" ]
    },

    {
      "DownstreamPathTemplate": "/api/product",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9002
        }
      ],
      "UpstreamPathTemplate": "/product",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath" :  "administration"
  }
}
           

4、運作網關項目驗證,通路http://localhost:9000/product進行驗證,localhost:9000是你網關項目的host

參考連結:https://www.cnblogs.com/yotsuki/p/7928095.html

繼續閱讀