最近在做一个分布式项目,目前到了整合阶段,突然发现接口文档十分分散,于是想要集成到一起。网上找了很多文章,对我都没有太大帮助,最后再几经辗转加上自己修改了一些代码后,终于成功了。
默认你的分布式架构已经搭建完毕,只差将全部的接口文档都整合到一个端口下。
如下:
第一步:
在你的Gateway和Provider中全部引入Jar:
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--swagger-ui 这里是用了一个好看一点ui界面-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
第二步:
在你的Provider中创建文件:SwaggerConfig.java
里面的一些信息记得改...
package com.zk.f.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 org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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.*;
@Configuration
public class SwaggerConfig implements WebMvcConfigurer {
//配置了Swagger的Docket的bean实例
//enable是否启动swagger,如果为False则Swagger不能在浏览器访问
@Bean
public Docket docket() {
Set<String> set = new HashSet<>();
set.add("https");
set.add("http");
return new Docket(DocumentationType.SWAGGER_2).pathMapping("/")
.enable(true)//定义是否开启swagger,false为关闭,可以通过变量控制
// 微信关注开发者技术前线:定义是否开启swagger,false为关闭,可以通过变量控制
.apiInfo(apiInfo())//将api的元信息设置为包含在json ResourceListing响应中。
.select()
.apis(RequestHandlerSelectors.basePackage("com.zk.f"))
//paths()过滤什么路径
.paths(PathSelectors.any())
.build()
.protocols(set)// 支持的通讯协议集合
.securitySchemes(securitySchemes())// 授权信息设置,必要的header token等认证信息
.securityContexts(securityContexts());// 授权信息全局应用
}
//作者信息
Contact contact = new Contact("kabit","www.baidu.com","kabit@sina.cn");
//配置Swagger 信息 = ApiInfo
private ApiInfo apiInfo()
{
return new ApiInfo("数字渔业网关Api文档",
"szyy",
"1.0",
"www.baidu.com",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
/**
* 设置授权信息
*/
private List<SecurityScheme> securitySchemes()
{
List<ApiKey> result = new ArrayList<>();
ApiKey apiKey = new ApiKey("Authorization","Authorization" ,"Header" );
result.add(apiKey);
return Collections.singletonList(apiKey);
}
/**
* 授权信息全局应用
*/
private List<SecurityContext> securityContexts() {
return Collections.singletonList(
SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("Authorization", new AuthorizationScope[]{new AuthorizationScope("global", "Authorization")})))
.build()
);
}
}
第三步:
在Gateway中创建文件:
SwaggerProvider.java
package com.zk.e.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
/**
* <p></p>
*
* @author kabit
* @createTime 2021/9/21 17:13
* @since 1.0
*/
@Component
@Primary
public class SwaggerProvider implements SwaggerResourcesProvider {
/**
* RouteLocator,GatewayProperties这两个类都是springcloud提供的springbean对象直接注入即可
*/
private final RouteLocator routeLocator;
//gateway配置文件
private final GatewayProperties gatewayProperties;
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routes = new ArrayList<>();
routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
//从配置文件中获取并配置SwaggerResource
gatewayProperties.getRoutes().stream()
//过滤路由
.filter(routeDefinition -> routes.contains(routeDefinition.getId()))
//循环添加,从路由的断言中获取,一般来说路由都会配置断言Path信息,这就不多说了
.forEach(route -> {
route.getPredicates().stream()
//获取Path信息
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
//开始添加SwaggerResource
.forEach(predicateDefinition -> resources.add(swaggerResource(route.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("**", "v2/api-docs"))));
});
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(DocumentationType.OAS_30.getVersion());
return swaggerResource;
}
@Autowired
public SwaggerProvider(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
this.routeLocator = routeLocator;
this.gatewayProperties = gatewayProperties;
}
}
附上我的Gateway部分配置文件:
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowedOrigins=*
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowedMethods[0]=GET
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowedMethods[1]=POST
spring.cloud.gateway.routes[0].id=auth
spring.cloud.gateway.routes[0].uri=http://localhost:8189
spring.cloud.gateway.routes[0].predicates[0]=Path=/auth/**
spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1
spring.cloud.gateway.routes[1].id=public-provider
spring.cloud.gateway.routes[1].uri=lb://public-provider
spring.cloud.gateway.routes[1].predicates[0]=Path=/public/**
spring.cloud.gateway.routes[1].filters[0]=StripPrefix=1
org.my.jwt.skip-auth-urls[0]=/auth
org.my.jwt.skip-auth-urls[1]=/public/v2/api-docs
最后http://ip+端口/doc.html#/访问就好了,如果不行的话,自己尝试改一改,毕竟我也是一路改过来的。
由于看了几十篇博客,真的忘了其中代码出自哪位大佬了。
十分感谢就完了~