.NET

.NET6集成Ocelot网关&Consul服务发现

2022-05-30  本文已影响0人  Charles2018

Program.cs

using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;

var builder = WebApplication.CreateBuilder(args);

//Ocelot///////////////////////////////////////////////////////////
builder.Configuration.SetBasePath(Directory.GetCurrentDirectory());
builder.Configuration.AddJsonFile("appsettings.json", true, true);
builder.Configuration.AddJsonFile("ocelot.json");
//Ocelot///////////////////////////////////////////////////////////
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//Ocelot///////////////////////////////////////////////////////////
builder.Services.AddOcelot()
    .AddConsul()
    .AddConfigStoredInConsul();
//Ocelot///////////////////////////////////////////////////////////
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
//Ocelot///////////////////////////////////////////////////////////
app.UseOcelot().Wait();
//Ocelot///////////////////////////////////////////////////////////
//app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Urls.Add("http://localhost:5000");

app.Run();

ocelot.json

{
  "Routes": [
    {
      "UpstreamPathTemplate": "/api/v1/{url}",
      "UpstreamHttpMethod": [ "Get" ],
      "DownstreamPathTemplate": "/api/ServiceApi1/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8000
        }
      ]
    },
    {
      "UpstreamPathTemplate": "/api/v2/{url}",
      "UpstreamHttpMethod": [ "Get" ],
      "DownstreamPathTemplate": "/api/ServiceApi2/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 8001
        }
      ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5000"
  },
  "ServiceDiscoveryProvider": {
    "Host": "localhost",
    "Port": 5000
  }
}

详细文档/Ocelot官网

上一篇 下一篇

猜你喜欢

热点阅读