当前位置: 首页 > news >正文

.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", // 服务绑定IPPort = 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
http://www.lryc.cn/news/516798.html

相关文章:

  • 使用 Nginx 轻松处理跨域请求(CORS)
  • 【LeetCode Hot100 二分查找】搜索插入位置、搜索二维矩阵、搜索旋转排序数组、寻找两个正序数组的中位数
  • 使用MediaPipe Face Mesh 面部动作检测
  • 【Vue】<script setup>和 <script>区别是什么?在使用时的写法区别?
  • 微服务框架,Http异步编程中,如何保证数据的最终一致性
  • vue3-dom-diff算法
  • 年会抽奖Html
  • ubuntu16 重启之后lvm信息丢失故障恢复
  • 【华为OD-E卷 - 热点网站统计 100分(python、java、c++、js、c)】
  • Ubuntu下安装Android Sdk
  • 【JVM】总结篇-类的加载篇之 类的加载器 和ClassLoader分析
  • 怎样修改el-table主题样式
  • MySQL(二)MySQL DDL数据库定义语言
  • Spring Boot 项目启动报 NoClassDefFoundError 异常的原因分析与解决方案 - jackson 版本不一致
  • 原型与原型链
  • 【Linux】信号处理
  • 5个不同类型的mysql数据库安装
  • python学习笔记—12—布尔类型、if语句
  • 分数阶傅里叶变换代码 MATLAB实现
  • 《数据结构》期末考试测试题【中】
  • openwrt 清缓存命令行
  • RP2K:一个面向细粒度图像的大规模零售商品数据集
  • .NET Core FluentAPI
  • 【C++数据结构——查找】顺序查找(头歌实践教学平台习题)【合集】
  • HTTP Scheme 通常指的是在 URL 中用于指定使用 HTTP 协议的方案(scheme)
  • 基于Matlab的变压器仿真模型建模方法(13):单相升压自耦变压器的等效电路和仿真模型
  • 【Vue.js】监听器功能(EventListener)的实际应用【合集】
  • 【Shell脚本】Docker构建Java项目,并自动停止原镜像容器,发布新版本
  • 【iOS Swift Moya 最新请求网络框架封装通用】
  • 前端批量下载文件