Spring Cloud gateway整合knife4j整合方案
1、首先导入依赖 在 服务端和网关都要有依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<knife4j.version>2.0.9</knife4j.version>
2、在gateway服务中写入配置类
@Component
@RequiredArgsConstructor
public class MySwaggerResourceProvider implements SwaggerResourcesProvider {
private static final String SWAGGER2_URL = "/v2/api-docs";
private final RouteLocator routeLocator;
@Value("${spring.application.name}")
private String gatewayName;
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routeHosts = new ArrayList<>();
routeLocator.getRoutes()
.filter(route -> route.getUri().getHost() != null)
.filter(route -> !gatewayName.equals(route.getUri().getHost()))
.subscribe(route -> routeHosts.add(route.getUri().getHost()));
for (String routeHost : routeHosts) {
String serviceUrl = "/" + routeHost + SWAGGER2_URL;
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setUrl(serviceUrl);
swaggerResource.setName(routeHost);
swaggerResource.setSwaggerVersion("3.0.0");
resources.add(swaggerResource);
}
return resources;
}
}
@RestController
@RequestMapping("/swagger-resources")
@RequiredArgsConstructor
public class SwaggerResourceController {
private final MySwaggerResourceProvider swaggerResourceProvider;
@RequestMapping
public ResponseEntity<List<SwaggerResource>> swaggerResources() {
return new ResponseEntity<>(swaggerResourceProvider.get(), HttpStatus.OK);
}
}
3、然后在每一个服务类都加swagger配置
@Configuration
@EnableSwagger2WebMvc
@EnableKnife4j
public class SwaggerConfiguration {
@Bean(value = "userApi")
@Order(value = 1)
public Docket groupRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(groupApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.li.graduation.vod.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo groupApiInfo() {
return new ApiInfoBuilder()
.title("swagger-bootstrap-ui很棒~~~!!!")
.description("<div style='font-size:14px;color:red;'>swagger-bootstrap-ui-demo RESTful APIs</div>")
.termsOfServiceUrl("http://www.group.com/")
.contact("group@qq.com")
.version("1.0")
.build();
}
}
访问网关就可以啦
地址:http://localhost:8333/doc.html localhost:网关端口/doc.html/
地址:http://localhost:8301/doc.html localhost:服务端口/doc.html/
参考文献:
https://yunyanchengyu.blog.csdn.net/article/details/121647923
|