.NET 8 + Ocelot + Consul 实现代理网关、服务发现

.NET 8 + Ocelot + Consul 实现代理网关、服务发现

本文环境:.NET 8 + Ocelot 23.4.2 + Consul 1.7.14.6

1 实现网关

  1. 分别创建3个WebApi工程:OcelotGwTestGwAServiceTestGwBService
  2. OcelotGw工程中安装Ocelot包:Install-Package Ocelot
  3. 添加JSON配置文件或直接在appsettings.json文件中添加配置;
    1. 配置内容:
    {
      "Routes": [
        {
          "DownstreamPathTemplate": "/api/{url}",
          "DownstreamScheme": "https",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5001
            }
        ],
        "UpstreamPathTemplate": "/A/{url}",
        "UpstreamHttpMethod": [ "Get" ]
        },
        {
          "DownstreamPathTemplate": "/api/{url}",
          "DownstreamScheme": "https",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 5002
            }
        ],
        "UpstreamPathTemplate": "/B/{url}",
        "UpstreamHttpMethod": [ "Get" ]
        },
        {
          "DownstreamPathTemplate": "/todos/{id}",
          "DownstreamScheme": "https",
          "DownstreamHostAndPorts": [
            {
              "Host": "jsonplaceholder.typicode.com",
              "Port": 443
            }
        ],
        "UpstreamPathTemplate": "/todos/{id}",
        "UpstreamHttpMethod": [ "Get" ]
        }
      ],
      "GlobalConfiguration": {
        "BaseUrl": "https://localhost:5000/"
      }
    }
    
  4. 在测试服务中分别添加HelloController
    [Route("api/[controller]")]
    [ApiController]
    public class HelloController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return Ok("Hello from Service A!");
        }
    }
    
  5. 同时启动三个工程,并访问https://localhost:5000/B/Hellohttps://localhost:5000/B/Hello测试。

2 服务发现

下面使用服务发现完成ServiceA的配置;

  1. 下载Consul:Install Consul
  2. 运行Consul,启动命令:consul.exe agent -dev
  3. 修改ServiceAOcelot配置:
    {
        "UseServiceDiscovery": true,
        "DownstreamPathTemplate": "/api/{url}",
        "DownstreamScheme": "http",
        "ServiceName": "ServiceA",
        "UpstreamPathTemplate": "/A/{url}",
        "UpstreamHttpMethod": [ "Get" ]
    }
    
  4. ServiceA中添加健康监测接口:
    using Microsoft.AspNetCore.Mvc;
    namespace Hearth.TestGwAService.Controllers
    {
        [Route("[controller]/[action]")]
        [ApiController]
        public class HealthController : ControllerBase
        {
            [HttpGet("/healthCheck")]
            public IActionResult Check() => Ok("ok");
        }
    }
    
  5. ServiceAProgram中进行代理服务注册:
    var consulClient = new ConsulClient(x =>
    {
        // consul 服务地址
        x.Address = new Uri("http://localhost:8500");
    });
    var registration = new AgentServiceRegistration()
    {
        ID = Guid.NewGuid().ToString(),
        Name = "ServiceA",// 服务名
        Address = "localhost", // 服务绑定IP
        Port = 5001, // 服务绑定端口
        Check = new AgentServiceCheck()
        {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
            Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔
            HTTP = "http://localhost:5001/healthCheck",//健康检查地址
            Timeout = TimeSpan.FromSeconds(5)
        }
    };
    // 服务注册
    consulClient.Agent.ServiceRegister(registration).Wait();
    var app = builder.Build();
    // 应用程序终止时,服务取消注册
    app.Lifetime.ApplicationStopping.Register(() =>
    {
        consulClient.Agent.ServiceDeregister(registration.ID).Wait();
    });
    

3 一些问题

  1. Ocelot配置文件中,旧版本可能用的是ReRoutes,新版本中应该是Routes
  2. 注意DownstreamScheme,如果使用ssl应为https
  3. 在开发环境使用Consul服务发现时,需要注意是否使用SSL验证,无效的证书会导致502 Bad Gateway;
  4. 官方文档:ocelot.readthedocs.io
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Winemonk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值