栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

gateway集成swagger

Java 更新时间:发布时间: 百科书网 趣学号

gateway集成swagger
    • 1、本次集成依赖gateway和swagger版本
    • 2、swagger配置
    • 3、重要事项(看看少踩坑)‼️
    • 4、gateway配置 因为gateway没有web包所以需要配置
    • 5、效果图
    • 6、有其他问题请留言评论,帮助到你请帮忙点个关注+赞谢谢

简单粗暴直接上代码

1、本次集成依赖gateway和swagger版本
		
        
            org.springframework.cloud
            spring-cloud-starter-gateway
            2.2.2.RELEASE
        

		
        
        
            io.springfox
            springfox-boot-starter
            3.0.0
        
2、swagger配置
package com.lc.api.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.documentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.*;


@Configuration
public class SwaggerConfig {

	@Value("${swagger.enable:true}")
	private Boolean enable;

	@Bean
	public Docket api() {
		return new Docket(documentationType.OAS_30)
				//资源
				.globalResponses(HttpMethod.GET, new ArrayList<>())
				.globalResponses(HttpMethod.PUT, new ArrayList<>())
				.globalResponses(HttpMethod.POST, new ArrayList<>())
				.globalResponses(HttpMethod.DELETE, new ArrayList<>())
				//是否启动
				.enable(enable)
				//头部信息
				.apiInfo(apiInfo())
				.select()
				
				.apis(RequestHandlerSelectors.any())
				//过滤某个路径
				.paths(PathSelectors.any())
				.build()
				//协议
				.protocols(newHashSet("https", "http"))
				.securitySchemes(securitySchemes())
				.securityContexts(securityContexts());
	}


	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("接口文档")
				.description("@author Teler")
				.contact(new Contact("Teler", null, "123@qq.com"))
				.version("1.0")
				.build();
	}

	
	private List securitySchemes() {
		return Collections.singletonList(new ApiKey("base_TOKEN", "token", "header"));
	}

	
	private List securityContexts() {
		return Collections.singletonList(
				SecurityContext.builder()
						.securityReferences(
								Collections.singletonList(new SecurityReference("base_TOKEN",
										new AuthorizationScope[]{new AuthorizationScope("global", "")}
								)))
						//.forPaths(PathSelectors.any())
						.build()
		);
	}

	@SafeVarargs
	private final  Set newHashSet(T... ts) {
		if (ts.length > 0) {
			return new linkedHashSet<>(Arrays.asList(ts));
		}
		return null;
	}
}

3、重要事项(看看少踩坑)‼️

注意事项:

  1. swagger3默认的url后缀 v3时默认不会拼接路由前缀 请求子服务时会缺少buseUrl(swagger请求子服务时会404 所以写v2版本就好)
  2. getData()这个方法是我自己用来截取路由自己配的路由的路径 也可以直接用route.getId() 需要注意的是用route.getId()需要你在路由里面配置的id跟pattern保持一致如下图跟我一样有不一致的情况就老老实实用我getData()方法来拼接URL**
  3. 其他gateway配置请参考一下链接
    gateway动态路由:https://blog.csdn.net/qq_41988504/article/details/107227870
    spring cloud集成nacos:https://blog.csdn.net/qq_41988504/article/details/105561281
    spring cloud集成gateway:https://blog.csdn.net/qq_41988504/article/details/102912531
    spring cloud集成nacos配置中心:https://blog.csdn.net/qq_41988504/article/details/105561281

4、gateway配置 因为gateway没有web包所以需要配置
package com.lc.gateway.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Component
@Primary
public class GatewaySwaggerResourcesProvider implements SwaggerResourcesProvider {

    
    public static final String SWAGGER2URL = "/v2/api-docs";
    
    private final RouteLocator routeLocator;

    
    @Value("${spring.application.name}")
    private String self;

    @Autowired
    public GatewaySwaggerResourcesProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    
    @Override
    public List get() {
        List resources = new ArrayList<>();
        List routeHosts = new ArrayList<>();
        // 获取所有可用的host:serviceId
        routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
                .filter(route -> !self.equals(route.getUri().getHost()))
                // 解决不会拼接路由里面的 pattern 打开swagger时无显示问题
                .subscribe(route -> routeHosts.add(getData(route.getPredicate().toString())+"/"+route.getUri().getHost()));

        // 记录已经添加过的server
        Set dealed = new HashSet<>();
        routeHosts.forEach(instance -> {
            // 拼接url
            String url = "/" + instance.toLowerCase() + SWAGGER2URL;
            if (!dealed.contains(url)) {
                dealed.add(url);
                SwaggerResource swaggerResource = new SwaggerResource();
                swaggerResource.setUrl(url);
                swaggerResource.setName(instance);
                swaggerResource.setSwaggerVersion("3.0.n");
                resources.add(swaggerResource);
            }
        });
        return resources;
    }

    
    public static String getData(String data) {
        List list = new ArrayList<>();
        Pattern p = Pattern.compile("(\[[^\]]*\])");
        Matcher m = p.matcher(data);
        while (m.find()) {
            list.add(m.group().substring(1, m.group().length() - 1));
        }
        if (!CollectionUtils.isEmpty(list)) {
            String s = list.get(0);
            return s.substring(s.indexOf("/") + 1, s.lastIndexOf("/"));
        }
        return null;
    }
}




5、效果图

6、有其他问题请留言评论,帮助到你请帮忙点个关注+赞谢谢
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/270213.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号