41.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--扩展功能--集成网关--网关集成Swagger

在这篇文章中讲解的网关集成Swagger的功能,主要是为了在网关层面上提供一个统一的API文档入口,方便再开发环境中前后端联调,在生产环境中是没有这个的。通过集成Swagger,我们可以在网关上直接访问所有微服务的API文档,而不需要单独访问每个微服务的Swagger UI。这种方式不仅提高了开发和测试的效率,还能让前端开发人员更方便地了解后端服务的接口。

要在网关项目中集成其他微服务的Swagger文档,我们首先要做的是在网关项目中安装MMLib.SwaggerForOcelot包,这个包可以帮助我们将Ocelot网关与Swagger集成起来。安装命令如下:

bash 复制代码
dotnet add package MMLib.SwaggerForOcelot

Tip:感谢开发MMLib.SwaggerForOcelot的大佬'Miňo Martiniak',GitHub地址:https://github.com/Burgyn/MMLib.SwaggerForOcelot

接下来,我们需要在网关的Program.cs文件中进行一些配置,以下是相关代码:

csharp 复制代码
// more code...
if (builder.Environment.IsDevelopment() || builder.Environment.EnvironmentName == "Local")
{
    // Swagger 配置
    builder.Services.AddSwaggerGen();
    builder.Services.AddSwaggerForOcelot(builder.Configuration);
}

// more code...

// 中间件管道
if (app.Environment.IsDevelopment() || app.Environment.EnvironmentName == "Local")
{
    app.UseSwagger();
    app.UseSwaggerForOcelotUI(opt =>
    {
        opt.PathToSwaggerGenerator = "/swagger/docs";
    });
}

// more code...

在上面代码中,我们首先检查当前环境是否为开发环境或本地环境,如果是,则添加Swagger生成器和Ocelot的Swagger支持。接着,在中间件管道中,我们使用UseSwagger()来启用Swagger文档生成,并使用UseSwaggerForOcelotUI()来配置Swagger UI的路径。

这些都配置完成后,我们就要在nacos中添加SwaggerConfig配置,具体内容如下:

json 复制代码
{
  "SwaggerConfig": {
    "GatewayTitle": "SporeAccounting Gateway API",
    "Version": "v1",
    "Description": "统一API网关 - 集成所有微服务的Swagger文档",
    "RoutePrefix": "swagger",
    "EnabledServices": [
      "identity",
      "config", 
      "currency",
      "finance",
      "report"
    ],
    "ServiceNameMapping": {
      "identity": "Identity Service",
      "config": "Config Service",
      "currency": "Currency Service",
      "finance": "Finance Service",
      "report": "Report Service"
    },
    "AliasToNacosServiceName": {
      "identity": "SPIdentityService",
      "config": "SPConfigService",
      "currency": "SPCurrencyService",
      "finance": "SPFinanceService",
      "report": "SPReportService"
    }
  },
  "SwaggerServices": [
    {
      "Name": "财务服务",
      "ServiceName": "SPFinanceService",
      "Description": "财务管理相关 API",
      "IsActive": true
    },
    {
      "Name": "身份服务",
      "ServiceName": "SPIdentityService",
      "Description": "用户身份认证相关 API",
      "IsActive": true
    },
    {
      "Name": "货币服务",
      "ServiceName": "SPCurrencyService",
      "Description": "货币管理相关 API",
      "IsActive": true
    },
    {
      "Name": "配置服务",
      "ServiceName": "SPConfigService",
      "Description": "系统配置相关 API",
      "IsActive": true
    },
    {
      "Name": "报表服务",
      "ServiceName": "SPReportService",
      "Description": "报表生成相关 API",
      "IsActive": true
    }
  ],
    "SwaggerEndPoints": [
    {
      "Key": "finance",
      "Config": [
        {
          "Name": "Finance Service",
          "Version": "v1",
          "Url": "http://localhost:8977/finance/swagger/v1/swagger.json"
        }
      ]
    },
    {
      "Key": "identity",
      "Config": [
        {
          "Name": "Identity Service",
          "Version": "v1",
          "Url": "http://localhost:8977/identity/swagger/v1/swagger.json"
        }
      ]
    },
    {
      "Key": "config",
      "Config": [
        {
          "Name": "Config Service",
          "Version": "v1",
          "Url": "http://localhost:8977/config/swagger/v1/swagger.json"
        }
      ]
    },
    {
      "Key": "currency",
      "Config": [
        {
          "Name": "Currency Service",
          "Version": "v1",
          "Url": "http://localhost:8977/currency/swagger/v1/swagger.json"
        }
      ]
    },
    {
      "Key": "report",
      "Config": [
        {
          "Name": "Report Service",
          "Version": "v1",
          "Url": "http://localhost:8977/report/swagger/v1/swagger.json"
        }
      ]
    }
  ]
}

在这个配置中,我们定义了网关的基本信息,如标题、版本和描述等。同时,我们指定了需要集成Swagger文档的微服务名称,并为每个微服务提供了别名和Nacos服务名称的映射。

最后一步,我们要修改ocelot.json配置,在每个Route配置下增加SwaggerKey属性,这个属性的值就是我们在SwaggerConfig中定义的Key名称。以下是一个示例:

json 复制代码
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/identity/{everything}",
      "UpstreamHttpMethod": ["GET", "POST", "PUT", "DELETE", "PATCH"],
      "ServiceName": "SPIdentityService",
      "UseServiceDiscovery": true,
      "LoadBalancerOptions": { "Type": "RoundRobin" },
      "SwaggerKey": "identity"  // 新增:匹配 SwaggerEndPoints 的 Key
    },
    // more configuration...
  ],
  // more configuration...
}

增加SwaggerKey属性后,Ocelot网关就能根据这个键值来匹配对应的Swagger文档配置。

这样配置完成后,我们就可以在浏览器中访问http://localhost:8977/swagger/index.html来查看所有微服务的Swagger文档了。

Tip:注意,SwaggerConfig配置和SwaggerKey属性只可以出现在开发环境和本地环境中,生产环境中一定不能有这个配置。

总结

通过以上步骤,我们成功地在Ocelot网关中集成了Swagger文档,使得所有微服务的API文档可以通过统一的入口访问。这种方式不仅提高了开发效率,还能让前端开发人员更方便地了解后端服务的接口。

在实际开发中,在本地和开发环境中使用这种集成方式,而在生产环境中则不能集成Swagger,以减少不必要的性能开销和安全风险。

相关推荐
天空属于哈夫克317 小时前
企业微信二次开发:精准实现关键词自动回复
架构·企业微信
小羊没烦恼!18 小时前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
晨米酱19 小时前
AGENTS.md:Agent 的上下文策略层
面试·架构·agent
这个DBA有点耶19 小时前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
码流子21 小时前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
moMo21 小时前
从固定流程到问题路由:让 LangGraph RAG 按需检索
架构
白远山1 天前
上海24小时自助健身房解决方案实战指南与经验分享
java·数据库·架构·需求分析
LorryJovens1 天前
【LAAP科研】双系统具身AGI范式研究——基于LAAP认知架构与Jev概率决策模型的系统性技术调研与范式验证
人工智能·gpt·安全·架构
JQweryuiop1 天前
中小型游戏陪练工作室数字化管理实践:基于七彩屋电竞护航小程序订单、履约与绩效系统的落地复盘
大数据·游戏·小程序·架构
LONGZETECH1 天前
一线职教实测:风光 580 汽车故障诊断仿真系统,破解实车实训四大核心痛点
人工智能·学习·安全·架构·汽车