SpringCloudGateway集成SpringDoc
最近在搞Spring版本升级,按客户要求升级Spring版本,原来用着SpringBoot 2.2.X版本,只需要升级SpringBoot 2.X最新版本也就可以满足客户Spring版本安全要求,可是好像最新的SpringBoot 2.X貌似也不支持Swagger2了,综合考虑,把项目的环境升级到SpringBoot3
版本
- SpringBoot 3.1.2
- SpringCloud 2022.0.3 (SpringCloudGateway 4.0.6)
- SpringDoc-OpenAPI 2.2.0
引入SpringDoc-OpenAPI依赖
<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webflux-api</artifactId><version>2.2.0</version>
</dependency>
<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webflux-ui</artifactId><version>2.2.0</version>
</dependency>
自动配置
思路
跟以前Swagger2集成Gateway差不多,读取Gateway的路由配置信息,刷新到SpringDoc-Swagger-UI属性去
实现
@Configuration
@ConditionalOnProperty(name = SPRINGDOC_ENABLED, matchIfMissing = true)
public class DocIntegrationConfig {@Autowiredprivate SwaggerUiConfigProperties swaggerUiConfigProperties;@Autowiredprivate RouteDefinitionLocator locator;@PostConstructpublic void apis() {//获取所有的路径配置List<RouteDefinition> definitions = locator.getRouteDefinitions().collectList().block();//过滤,只要lb模块式List<RouteDefinition> serviceRoutes = definitions.stream().filter(route -> null != route.getUri() && route.getUri().getScheme().equals("lb")).collect(Collectors.toList());//按根据PredicateDefinition参数值和/** 确定是否路径匹配Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> lbRouteUrl = new HashSet<>();Optional.ofNullable(serviceRoutes).orElse(Collections.emptyList()).forEach(route -> {AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl();//获取路径前缀List<PredicateDefinition> predicates = route.getPredicates();if (null == predicates || predicates.size() <= 0) {return;}String prefix = "";for (PredicateDefinition predicate : predicates) {String predicateName = predicate.getName();if ("path".equalsIgnoreCase(predicateName)) {for (String regex : predicate.getArgs().values()) {if (regex.endsWith("/**")) {prefix = regex.substring(0, regex.length() - 3);continue;}}}}//不是路径匹配的路由,跳过if (StringUtils.isBlank(prefix)) {return;}swaggerUrl.setUrl(prefix + Constants.DEFAULT_API_DOCS_URL);swaggerUrl.setName(prefix);swaggerUrl.setDisplayName(route.getId());lbRouteUrl.add(swaggerUrl);});//添加swaggerUI服务集成匹配if (lbRouteUrl.size() > 0) {Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> propertiesUrls = swaggerUiConfigProperties.getUrls();if (null == propertiesUrls || propertiesUrls.size() <= 0) {propertiesUrls = lbRouteUrl;} else {propertiesUrls.addAll(lbRouteUrl);}swaggerUiConfigProperties.setUrls(propertiesUrls);}}
}
然后就可以根据gateway的路由配置,自动在gateway springdoc界面生成各服务项,选择就可以查看该服务的在线文档。
借助swagger-ui.urls手动配置
springdoc,也提供配置的形式集成,配置swagger-ui.urls,就可以了,name为显示名称,url为服务api-docs,默认 /v3/api-docs。
springdoc:api-docs:#是否开启文档功能,默认为true,可不配置enabled: truewebjars:# 设置为空,不要前缀prefix:swagger-ui:path: /doc.htmlurls:- name: 网关服务接口url: /v3/api-docs- name: 某某服务接口url: /xxxx/v3/api-docs
在集成页面的右上角可看到配置的服务项,选择具体的服务
集成后CORS问题,请求查看下一篇文章