1 需求
因为开发需求,需要整合各个服务的接口文档,发现了knife4j最新版本(2023.3)出来了一个好用的插件,可以方便整合 SpringCloud Gateway 与各个业务服务的接口文档,不需要之前我们再硬编码写各种过滤器和拦截器去手动整合了。
2 官方文档
https://doc.xiaominfo.com/docs/middleware-sources/spring-cloud-gateway/spring-gateway-introduction
3 集成
值得注意的事项:
- 生产环境上线时,配置文件通过配置
knife4j.gateway.enabled: false进行关闭,避免接口泄漏,造成安全问题 - 支持服务发现
knife4j.gateway.discover.enabled: true,该属性4.1.0后新增 - 服务发现中注意排除网关服务
3.1 网关模块改造
3.1.1 增加依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-gateway-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
3.1.2 增加配置
knife4j:
gateway:
# 开启gateway聚合组件
enabled: true
# 服务发现自动聚合(discover)
strategy: discover
discover:
version: openapi3
enabled: true
# 排除不需要聚合的子服务,基于正则表达式(支持多个)
excluded-services:
# 排除gateway开头的服务
- gateway.*
# 排除服务中包含gateway字样的服务
- .*?gateway.*
# 排除shop-gateway服务
- shop-gateway
excluded-services:即为排除的网关服务的名称,
strategy: discover 是依赖 nacos的注册中心的服务发现模式,可以自动发现注册的业务服务
3.1.3 AuthGlobalFilter放开token验证
package com.example.gateway.filters;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import

本文档介绍了如何使用最新版Knife4J来整合SpringCloud Gateway接口文档,简化了原本的手动整合过程。详细步骤包括:网关模块改造,添加依赖和配置,放开AuthGlobalFilter的token验证;业务模块改造,添加依赖和配置;所有服务增加特定配置类,并提供了官方文档链接供参考。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



