Spring Cloud Gateway网关下的文档聚合(knife4j)
    		       		warning:
    		            这篇文章距离上次修改已过432天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Cloud Gateway网关下使用Knife4j进行文档聚合,你需要首先配置好Knife4j,并确保所有需要被文档化的服务都已经接入Knife4j。以下是一个简化的步骤和示例代码:
- 在每个服务中添加Knife4j依赖:
 
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>- 在每个服务的
application.yml或application.properties中配置Knife4j: 
# 配置Knife4j
knife4j.enable=true
knife4j.basic=
  username: your-username
  password: your-password- 在网关服务中,使用Knife4j提供的
SwaggerResource类来获取各个服务的Swagger配置,并通过Spring Cloud Gateway的路由功能将这些配置暴露出来。 
示例代码:
@Configuration
public class Knife4jConfig {
 
    @Autowired(required = false)
    private List<RouteLocator> routeLocators = new ArrayList<>();
 
    @Autowired
    private GatewayProperties gatewayProperties;
 
    @Bean
    public SwaggerResourcesProvider swaggerResourcesProvider() {
        return () -> {
            List<SwaggerResource> resources = new ArrayList<>();
            routeLocators.forEach(routeLocator -> routeLocator.getRoutes().forEach(route -> {
                // 假设服务名称和服务路径相同
                String serviceName = route.getId();
                resources.add(swaggerResource(serviceName, route.getUri().toString() + "/v2/api-docs"));
            }));
            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;
    }
}- 在网关服务中创建一个Controller来响应Knife4j的文档请求:
 
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerHandler {
    @Autowired
    private SwaggerResourcesProvider swaggerResourcesProvider;
 
    @GetMapping("/configuration/security")
    public ResponseEntity<SecurityConfiguration> securityConfiguration() {
        return ResponseEntity.ok(new SecurityConfiguration("basicAuth", new ArrayList<>()));
    }
 
    @GetMapping("/configuration/ui")
    public ResponseEntity<UiConfiguration> uiConfiguration() {
        return ResponseEntity.ok(new UiConfiguration(null, null, null, null, UiConfiguration.Constants.OPERATION_NONE, 1000L));
    }
 
    @GetMapping("/")
    public ResponseEntity<List<SwaggerResource>> swaggerResources() {
        retur           
评论已关闭