.Net6基于Ocelot搭建网关服务

发布时间 2023-05-04 17:06:21作者: kele-cc

网关大家都知道有什么用,就是很多个服务配置统一的入口访问地址。Ocelot有很多操作,比如负载均衡、限流、缓存、熔断
这篇就只说基础的配置。

新建一个名为Ocelot.Server.Net6的空项目,引用包源Ocelot

添加ocelot.json文件

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/{url}",
      "DownstreamScheme": "http",
	  // 下游服务的Method只能配置一个,不能配置成数组
      //"DownstreamHttpMethod": "POST",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        },
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/api/v1/{url}",
      "UpstreamHttpMethod": [
        "GET",
        "POST"
      ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" // RoundRobin负载均衡
      }
    }
  ],
  "GlobalConfiguration": {
  	// 网关服务的访问地址
    "BaseUrl": "http://localhost:5000",
    "Logging": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft.AspNetCore": "Warning"
      }
    }
  }
}

UpstreamPathTemplate为前端或客户端访问的路由
DownstreamPathTemplate为网关访问实际接口的路由
如上面这个配置,前端或客户端访问的地址则是http://localhost:5000/api/v1/OcelotTest/GetOcelotTest

Program注入 两种都可以

// var config = new ConfigurationBuilder()
//     .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
//     .Build();
// builder.Services.AddOcelot(config);

builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot();

app.UseOcelot().Wait();

新建Web.API.Test1Web.API.Test2的.Net6项目修改端口号分别为5001、5002

两个项目都添加OcelotTestController

using Microsoft.AspNetCore.Mvc;

namespace Web.API.Test1.Controllers;

[ApiController]
[Route("[controller]")]
public class OcelotTestController : ControllerBase
{
    [HttpGet("GetOcelotTest")]
    public IActionResult GetOcelotTest()
    {
        return Ok("DateTime:" + DateTime.Now + "--Port:5001"); // 区分这次请求的是哪个服务
    }
}

使用postman请求
image
image