这篇文章主要介绍“Gateway+Swagger2配置聚合文档的方法是什么”,在日常操作中,相信很多人在Gateway+Swagger2配置聚合文档的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Gateway+Swagger2配置聚合文档的方法是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
Spring Cloud Gateway网关模块聚合各微服务的Swagger接口文档
<!-- 网关路由代理 (仅网关)--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> <version>2.2.5.RELEASE</version> </dependency> <!--swagger2 (网关和服务端)--> <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.7.0.RELEASE</version> </dependency>
因为Swagger暂不支持webflux项目,所以Gateway里不能配置SwaggerConfig
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; /** * 功能描述: 采用路由id做资源名称,predicates.Path做映射的方式. * 如果需要自定义资源名称,可以单独配置一个集合(route.id,name),创建swaggerResource时, * 通过route.id获取name. * <p>例如: swagger: * route_names: * - name: 订单 * id: order_route * - name: 订单1 * id: order_route1 * spring: cloud: gateway: routes: * - id: order_route * - id: order_route1 * </p> * 重新Gateway的方法还没研究出来 - -|| * * @Author: * @Date: 2021-04-25 15:38 * @Version 1.0 **/ @Component @Primary public class Swagger2 implements SwaggerResourcesProvider { protected static final String API_URI = "/v2/api-docs";//固定后缀 private final RouteLocator routeLocator; private final GatewayProperties gatewayProperties; //资源集合 private static List<SwaggerResource> resources; //自定义资源名称需要在这里初始化 public Swagger2(RouteLocator routeLocator, GatewayProperties gatewayProperties) { this.routeLocator = routeLocator; this.gatewayProperties = gatewayProperties; } @Override public List<SwaggerResource> get() { //做了一个简单缓存,没仔细设计,其实可有可无用处不大 if (resources == null) { resources = new ArrayList<>(); List<String> routes = new ArrayList<>(); routeLocator.getRoutes().subscribe(route -> routes.add(route.getId())); //结合配置的route-路径(Path),和route过滤,只获取有效的route节点 gatewayProperties.getRoutes().stream() .filter(routeDefinition -> routes.contains(routeDefinition.getId())) .forEach(routeDefinition -> routeDefinition.getPredicates().stream() .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName())) .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0") .replace("/**", API_URI))))); } 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; } }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; import springfox.documentation.swagger.web.*; import java.util.Optional; @RestController @RequestMapping("/swagger-resources") public class SwaggerHandler { @Autowired(required = false) private SecurityConfiguration securityConfiguration; @Autowired(required = false) private UiConfiguration uiConfiguration; private final SwaggerResourcesProvider swaggerResources; @Autowired public SwaggerHandler(SwaggerResourcesProvider swaggerResources) { this.swaggerResources = swaggerResources; } @GetMapping("/configuration/security") public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() { return Mono.just(new ResponseEntity<>( Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK)); } @GetMapping("/configuration/ui") public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() { return Mono.just(new ResponseEntity<>( Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK)); } @GetMapping("") public Mono<ResponseEntity> swaggerResources() { //入口 return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK))); } }
使用swagger 的 try it out 功能发现路径错误,缺少服务器映射前缀的时候在用下面的过滤器.swagger 在拼装URL 数据时候,会增加X-Forwarder-Prefix 请求头里面的信息为前缀
import org.apache.commons.lang.StringUtils; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; @Component public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory { private static final String HEADER_NAME = "X-Forwarded-Prefix"; @Override public GatewayFilter apply(Object config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); String path = request.getURI().getPath(); if (!StringUtils.endsWithIgnoreCase(path, Swagger2.API_URI)) { return chain.filter(exchange); } String basePath = path.substring(0, path.lastIndexOf(Swagger2.API_URI)); ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build(); ServerWebExchange newExchange = exchange.mutate().request(newRequest).build(); return chain.filter(newExchange); }; } }
配置文件
spring: cloud: gateway: routes: #路由的ID,没有固定规则但要求唯一,简易配合服务名 - id: order_route #匹配后提供服务的路由地址 #uri: http://localhost:8001 #匹配后提供服务的路由地址,lb后跟提供服务的微服务的名,不要写错 uri: lb://order #断言 predicates: #路径相匹配的进行路由 - Path=/order/** #过滤掉url里的city,例如http://ip:port/city/getCity -> http://ip:port/getCity #filters: # - RewritePath=/city/(?<segment>.*), /$\{segment} filters: # - SwaggerHeaderFilter - StripPrefix=1 #不要忘了
服务端
import org.springframework.beans.factory.annotation.Value; 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.service.ApiInfo; import springfox.documentation.service.ApiKey; import springfox.documentation.service.AuthorizationScope; import springfox.documentation.service.SecurityReference; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; /** * 功能描述: Swagger2 接口文档 * * @Author: * @Date: 2021-04-23 15:59 * @Version 1.0 **/ @Configuration @EnableSwagger2 public class Swagger2 { //是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置 @Value(value = "${swagger.enabled}") private Boolean swaggerEnabled; //显示文档版本 @Value(value = "${swagger.version}") private String version; //标题 @Value(value = "${swagger.title}") private String title; //描述信息 @Value(value = "${swagger.description}") private String description; //扫描接口位置 也可以配置到nacos中 private static final String base_package = "com.demo.controller"; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2)// 指定api类型为swagger2 .apiInfo(apiInfo())// 用于定义api文档汇总信息 // 是否开启 .enable(swaggerEnabled).select() // 扫描的路径包 .apis(RequestHandlerSelectors.basePackage(base_package)) // 指定路径处理PathSelectors.any()代表所有的路径 .paths(PathSelectors.any()).build() .pathMapping("/") .securitySchemes(securitySchemes()) .securityContexts(securityContexts()); } //securitySchemes的ApiKey中增加一个名为“Authorization”,type为“header”的参数 private List<ApiKey> securitySchemes() { List<ApiKey> apiKeyList = new ArrayList(); apiKeyList.add(new ApiKey("Authorization", "Authorization", "header")); return apiKeyList; } private List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; List<SecurityReference> securityReferences = new ArrayList<>(); securityReferences.add(new SecurityReference("Authorization", authorizationScopes)); return securityReferences; } private List<SecurityContext> securityContexts() { List<SecurityContext> securityContexts = new ArrayList<>(); securityContexts.add( SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!auth).*$")) .build()); return securityContexts; } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(title)// 文档页标题 .contact(new Contact("s","s.com","s@163.com"))// 详细信息 .version(version)// 文档版本号 .termsOfServiceUrl("www.baidu.com")// 网站地址 .description(description) .build(); } } ```java
到此,关于“Gateway+Swagger2配置聚合文档的方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。