java · 2024年5月9日 0

SpringCloud中使用gateway集成swagger

一,在网关中配置每个服务的swagger服务路由规则

二,实现 SwaggerResourcesProvider 接口,用于重写SwaggerResource资源列表

三,配置swagger服务的请求跳转

/**
 * 用于 swagger 的请求跳转
 * */
@RestController
@RequestMapping("swagger/documentation")
public class SwaggerProxyController {

    private final DiscoveryClient discoveryClient;

    private final WebClient.Builder webClientBuilder;

    @Lazy
    @Autowired
    public SwaggerProxyController(DiscoveryClient discoveryClient,
                                  WebClient.Builder webClientBuilder){
        this.discoveryClient = discoveryClient;
        this.webClientBuilder = webClientBuilder;
    }

    /**
     * 根据路由规则,所有的swagger文档接口会请求到这里,然后在这个方法里面将请求通过代理到真实的服务上去
     * */
    @GetMapping("{serverName}/v2/api-docs")
    public Mono<String> proxy(@PathVariable("serverName") String serverName){
        // 在注册中心获取服务的真实地址
        List<ServiceInstance> instances = discoveryClient.getInstances(serverName);
        if (!CollectionUtils.isEmpty(instances)){
            ServiceInstance serviceInstance = instances.get(0);
            // 对应服务的swagger请求路径
            String uri = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() +"/v2/api-docs";
            return webClientBuilder.build().get()
                    .uri(uri)
                    .retrieve()
                    .bodyToMono(String.class);
        }

        return null;
    }

}

四,配置swagger聚合接口,访问swagger页面需要请求的接口

效果