简单粗暴直接上代码
<!--gateway网关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<!--swagger -->
<!-- 3.0版本只需要引入一个,不再像2.x版本需要引入两个包 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
package com.lc.api.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.*;
/**
* swagger配制
*
* @author lc
* @date 2021-9-25
*/
@Configuration
public class SwaggerConfig {
@Value("${swagger.enable:true}")
private Boolean enable;
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
//资源
.globalResponses(HttpMethod.GET, new ArrayList<>())
.globalResponses(HttpMethod.PUT, new ArrayList<>())
.globalResponses(HttpMethod.POST, new ArrayList<>())
.globalResponses(HttpMethod.DELETE, new ArrayList<>())
//是否启动
.enable(enable)
//头部信息
.apiInfo(apiInfo())
.select()
/**
* RequestHandlerSelectors,配置要扫描接口的方式
* basePackage指定要扫描的包
* any()扫描所有,项目中的所有接口都会被扫描到
* none()不扫描
* withClassAnnotation()扫描类上的注解
* withMethodAnnotation()扫描方法上的注解
*/
.apis(RequestHandlerSelectors.any())
//过滤某个路径
.paths(PathSelectors.any())
.build()
//协议
.protocols(newHashSet("https", "http"))
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
/**
* API 页面上半部分展示信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("@author Teler")
.contact(new Contact("Teler", null, "[email protected]"))
.version("1.0")
.build();
}
/**
* 设置接口单独的授权信息
*/
private List<SecurityScheme> securitySchemes() {
return Collections.singletonList(new ApiKey("BASE_TOKEN", "token", "header"));
}
/**
* 授权信息全局应用
*/
private List<SecurityContext> securityContexts() {
return Collections.singletonList(
SecurityContext.builder()
.securityReferences(
Collections.singletonList(new SecurityReference("BASE_TOKEN",
new AuthorizationScope[]{new AuthorizationScope("global", "")}
)))
//.forPaths(PathSelectors.any())
.build()
);
}
@SafeVarargs
private final <T> Set<T> newHashSet(T... ts) {
if (ts.length > 0) {
return new LinkedHashSet<>(Arrays.asList(ts));
}
return null;
}
}
注意事项:
package com.lc.gateway.server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* swagger的配置类
*
* @author lc
*/
@Component
@Primary
public class GatewaySwaggerResourcesProvider implements SwaggerResourcesProvider {
/**
* swagger3默认的url后缀 v3时默认不会拼接路由前缀 请求子服务时会缺少buseUrl
*/
public static final String SWAGGER2URL = "/v2/api-docs";
/**
* 网关路由
*/
private final RouteLocator routeLocator;
/**
* 网关应用名称
*/
@Value("${spring.application.name}")
private String self;
@Autowired
public GatewaySwaggerResourcesProvider(RouteLocator routeLocator) {
this.routeLocator = routeLocator;
}
/**
* 对于gateway来说这块比较重要 让swagger能找到对应的服务
*
* @return
*/
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routeHosts = new ArrayList<>();
// 获取所有可用的host:serviceId
routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
.filter(route -> !self.equals(route.getUri().getHost()))
// 解决不会拼接路由里面的 pattern 打开swagger时无显示问题
.subscribe(route -> routeHosts.add(getData(route.getPredicate().toString())+"/"+route.getUri().getHost()));
// 记录已经添加过的server
Set<String> dealed = new HashSet<>();
routeHosts.forEach(instance -> {
// 拼接url
String url = "/" + instance.toLowerCase() + SWAGGER2URL;
if (!dealed.contains(url)) {
dealed.add(url);
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setUrl(url);
swaggerResource.setName(instance);
swaggerResource.setSwaggerVersion("3.0.n");
resources.add(swaggerResource);
}
});
return resources;
}
/**
* 获取配置的路由name
* @param data
* @return
*/
public static String getData(String data) {
List<String> list = new ArrayList<>();
Pattern p = Pattern.compile("(\\[[^\\]]*\\])");
Matcher m = p.matcher(data);
while (m.find()) {
list.add(m.group().substring(1, m.group().length() - 1));
}
if (!CollectionUtils.isEmpty(list)) {
String s = list.get(0);
return s.substring(s.indexOf("/") + 1, s.lastIndexOf("/"));
}
return null;
}
}