springcloudAlibaba整合knife4j整合swagger整合gateway,并且同步到Yapi上
1.gateway模块
1.pom引入
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
2.代码层面,两个java文件
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;
import java.util.Optional;
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerHandler {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
private final SwaggerResourcesProvider swaggerResources;
@Autowired
public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
this.swaggerResources = swaggerResources;
}
@GetMapping("/configuration/security")
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("/configuration/ui")
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("")
public Mono<ResponseEntity> swaggerResources() {
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
}
}
import lombok.AllArgsConstructor;
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.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
public static final String API_URI = "/v2/api-docs";
private final RouteLocator routeLocator;
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()));
gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("/**", API_URI)))));
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
2.其他微服务模块,例如用户服务
1.pom引入同上
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
2.新建配置类 Swagger2Config
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
@EnableKnife4j
@ConfigurationProperties(prefix="swagger")
@Getter
@Setter
public class Swagger2Config {
private String title;
private String contact;
private String version;
private String license;
private String licenseUrl;
private String termsOfServiceUrl;
private String description;
private String basePackage;
/**
* 创建RestApi 并包扫描controller
* @return
*/
@Bean
public Docket createRestApi() {
List<Parameter> pars = new ArrayList<Parameter>();
ParameterBuilder token = new ParameterBuilder();
token.name("token").description("token")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build();
pars.add(token.build());
// pars.add(accessToken.build());
// ApiSelector.DEFAULT.getRequestHandlerSelector()
Predicate<RequestHandler> predicate = RequestHandlerSelectors.withClassAnnotation(Api.class);
predicate = Predicates.or(predicate, RequestHandlerSelectors.withClassAnnotation(ApiModel.class));
predicate = Predicates.or(predicate, RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//分组名称
// .groupName("2.X版本")
.select()
// // 对所有api进行监控
// .apis(RequestHandlerSelectors.any())
// .apis(RequestHandlerSelectors.basePackage(basePackage))
//不显示错误的接口地址
.paths(PathSelectors.any())
//错误路径不监控
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.globalOperationParameters(pars);
}
/**
* 创建Swagger页面 信息
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().
title(title).
contact(contact).
version(version).
license(license).
licenseUrl(licenseUrl).
termsOfServiceUrl(termsOfServiceUrl).
description(description)
.build();
}
}
3.配置yml
swagger:
enabled: true
title: 用户服务
# base-package: com.carbonease.procostra
version: V2.0
description: 用户服务
license: Apache License, Version 2.0
license-url: https://www.apache.org/licenses/LICENSE-2.0.html
terms-of-service-url: http://localhost:${server.port}/doc.html
contact: wzw13407261642@126.com
authorization: #有auth2 并使用以前的swagger-ui
key-name: Authorization
大功告成:
swagger地址:http://127.0.0.1:18000/swagger-ui.html#/
knife4j地址:http://127.0.0.1:18000/doc.html#/home
将api同步到Yapi
这里 项目的swagger json地址 就是下面swagger中的地址,但是需要能访问到,我这里测试所以用内网穿透测试了一下没问题,只要遵循swagger的api书写了,相关的注释都会同步到Yapi上
优化
如果微服务变多,那么每个服务都需要 加业务服务中的Swagger2Config,可以将 Swagger2Config 和 需要的pom抽取到一个公共模块中,业务模块只需要引入然后配置yml内容即可。
1.新建模块 swagger-starter
2.模块中引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
3.写配置类
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
@EnableKnife4j
@ConfigurationProperties(prefix = "swagger")
@ConditionalOnProperty(prefix = "swagger",name = "enabled",havingValue = "true")
@Data
public class Swagger2Config {
private String title;
private String contact;
private String version;
private String license;
private String licenseUrl;
private String termsOfServiceUrl;
private String description;
private String basePackage;
/**
* 创建RestApi 并包扫描controller
*
* @return
*/
@Bean
public Docket createRestApi() {
List<Parameter> pars = new ArrayList<Parameter>();
ParameterBuilder token = new ParameterBuilder();
token.name("token").description("token")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build();
pars.add(token.build());
// pars.add(accessToken.build());
// ApiSelector.DEFAULT.getRequestHandlerSelector()
Predicate<RequestHandler> predicate = RequestHandlerSelectors.withClassAnnotation(Api.class);
predicate = Predicates.or(predicate, RequestHandlerSelectors.withClassAnnotation(ApiModel.class));
predicate = Predicates.or(predicate, RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//分组名称
// .groupName("2.X版本")
.select()
// // 对所有api进行监控
// .apis(RequestHandlerSelectors.any())
// .apis(RequestHandlerSelectors.basePackage(basePackage))
//不显示错误的接口地址
.paths(PathSelectors.any())
//错误路径不监控
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.globalOperationParameters(pars);
}
/**
* 创建Swagger页面 信息
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().
title(title).
contact(contact).
version(version).
license(license).
licenseUrl(licenseUrl).
termsOfServiceUrl(termsOfServiceUrl).
description(description)
.build();
}
}
- 在resources下新建 META-INF,在 META-INF 下新建文件 spring.factories ,内容如下
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.wzw.swaggerstarter.config.Swagger2Config
5.业务模块工程引入此模块,网关模块请勿引入此模块
<dependency>
<groupId>com.wzw</groupId>
<artifactId>swagger-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
6.在业务模块中配置yml文件
swagger:
enabled: false
title: entry服务
# base-package: com.carbonease.procostra
version: V2.0
description: entry服务
license: Apache License, Version 2.0
license-url: https://www.apache.org/licenses/LICENSE-2.0.html
terms-of-service-url: http://localhost:${server.port}/doc.html
contact: wzw13407261642@126.com
authorization: #有auth2 并使用以前的swagger-ui
key-name: Authorization