目录
背景
各个微服务都有自己的Swagger文档,当使用Gateway做为微服务统一入口时,如何对外统一暴露微服务的Swagger呢?这篇文章继续演示Gateway聚合各个微服务的Swagger的能力,以最小依赖为原则,不依赖注册中心,以便聚焦如何展示Swagger这部分的功能。
本文开发环境介绍
开发依赖 | 版本 |
---|---|
Spring Boot | 2.7.0 |
Spring Cloud | 2021.0.1 |
Spring Cloud Alibaba | 2021.0.1.0 |
搭建一个微服务
微服务需要提供Swagger
pom.xml的依赖如下
<properties>
<springfox-boot-starter.version>3.0.0</springfox-boot-starter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${springfox-boot-starter.version}</version>
</dependency>
</dependencies>
开启Swagger
import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerAutoConfiguration {
@Bean
public Docket onlineDocApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo("Controller接口", "接口文档", "1.0"))
.select()
.apis( RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(String name, String description, String version) {
return new ApiInfoBuilder()
.title(name)
.description(description)
.contact(new Contact("demo", null, null))
.version(version).build();
}
}
application.yml如下
server:
port: 8082
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
运行main函数启动微服务
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
访问微服务Swagger
在浏览器输入http://localhost:8082/swagger-ui/index.html
说明这个微服务的Swagger已经正常开启了
Gateway入门
如果还不熟悉Gateway的可以参考上一篇写的Gateway入门
Gateway配置
pom.xml
依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${springfox-boot-starter.version}</version>
</dependency>
</dependencies>
转发配置示例
application.yml
配置如下
server:
port: 8081
spring:
application:
name: demo-gateway
mvc:
pathmatch:
matching-strategy: ant_path_matcher
cloud:
gateway:
#路由配置
routes:
- id: demoSwagger
uri: http://localhost:8082
predicates:
- Path=/demo/**
filters:
- StripPrefix=1
实现SwaggerResourcesProvider接口
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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;
@RequiredArgsConstructor
@Slf4j
@Component
@Primary
public class SwaggerProvider implements SwaggerResourcesProvider {
/**swagger2默认的url后缀*/
private static final String SWAGGER_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<>();
// 只抽取后缀为Swagger的路由信息
routeLocator.getRoutes()
.filter(route -> route.getId().endsWith("Swagger"))
.subscribe(route -> routes.add(route.getId()));
gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())).forEach(route -> {
route.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(route.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("/**", SWAGGER_URI))));
});
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
log.info("name:{},location:{}",name,location);
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
return swaggerResource;
}
}
重写Swagger的数据接口
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger.web.*;
import java.util.List;
@RequiredArgsConstructor
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {
private final SwaggerProvider swaggerResourceProvider;
@RequestMapping(value = "/configuration/security")
public ResponseEntity<SecurityConfiguration> securityConfiguration() {
return new ResponseEntity<>(SecurityConfigurationBuilder.builder().build(), HttpStatus.OK);
}
@RequestMapping(value = "/configuration/ui")
public ResponseEntity<UiConfiguration> uiConfiguration() {
return new ResponseEntity<>(UiConfigurationBuilder.builder().build(), HttpStatus.OK);
}
@RequestMapping
public ResponseEntity<List<SwaggerResource>> swaggerResources() {
return new ResponseEntity<>(swaggerResourceProvider.get(), HttpStatus.OK);
}
}
启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;
@EnableOpenApi
@SpringBootApplication
public class DemoGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(DemoGatewayApplication.class, args);
}
}
Swagger访问测试
在浏览器输入http://localhost:8081/swagger-ui
看到的Swagger与8082
端口的微服务是一样的
总结
我们在开发微服务的过程中,由于各种原因,会引入API网关,那么之前直接由微服务对外提供的Swagger文档,也同样希望可以通过API网关统一对外展示,本文通过最小依赖,使用极简的方式演示了Gateway如何聚合后端微服务的Swagger文档,希望可以帮助到大家少走一点弯路。