验证中...
Languages: Java
Categories: 软件配置
Latest update 2018-12-09 10:38
Snippet 1 Snippet 2 Snippet 3 Snippet 4 Snippet 5 Snippet 6 Snippet 7 Snippet 8 Snippet 9
网关端-pom.xml
Raw Copy
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- for swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- for swagger -->
网关端-SwaggerProvider.java
Raw Copy
package xin.gate.config;
import lombok.AllArgsConstructor;
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;
/**
* <pre>
* Swagger Provider
* </pre>
*
* @author lixin_ma@outlook.com
* @version 1.0
* @since 2018/10/22
*/
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
public static final String API_URI = "/v2/api-docs";
public static final String PATH = "Path";
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routes = new ArrayList<>();
//取出gateway的route
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;
}
}
网关端-SwaggerHeaderFilter.java
Raw Copy
package xin.gate.filter;
import xin.gate.config.SwaggerProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.tuple.Tuple;
import org.springframework.web.server.ServerWebExchange;
/**
* <pre>
* Swagger Header Filter
* </pre>
*
* @author lixin_ma@outlook.com
* @version 1.0
* @since 2018/10/22
*/
@Component
@Slf4j
public class SwaggerHeaderFilter implements GatewayFilterFactory {
private static final String HEADER_NAME = "X-Forwarded-Prefix";
@Override
public GatewayFilter apply(Tuple args) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
return chain.filter(exchange);
}
String basePath = path.substring(0, path.lastIndexOf(SwaggerProvider.API_URI));
log.info("SwaggerHeaderFilter X-Forwarded-Prefix :{}",basePath);
ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
return chain.filter(newExchange);
};
}
}
网关端-SwaggerHandler.java
Raw Copy
package xin.gate.handle;
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;
/**
* <pre>
* Swagger Handler
* </pre>
*
* @author lixin_ma@outlook.com
* @version 1.0
* @since 2018/10/22
*/
@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)));
}
}
网关端-application.yml
Raw Copy
spring:
cloud:
gateway:
locator:
enabled: true
routes:
# =====================================
- id: server1
uri: lb://server1
order: 8000
predicates:
- Path=/api/server1/**
filters:
- SwaggerHeaderFilter
- StripPrefix=2
# =====================================
- id: server2
uri: lb://server2
order: 8001
predicates:
- Path=/server2/**
filters:
- StripPrefix=1
# =====================================
- id: server2
uri: lb://server2
order: 8001
predicates:
- Path=/api/server2/**
filters:
- SwaggerHeaderFilter
- StripPrefix=2
# =====================================
server端-pom.xml
Raw Copy
<!-- 也可以使用原生的swagger -->
<!-- spring4all 的话配置简单一些,只需要在启动类上添加@EnableSwagger2Doc注解然后在applicaiton.yml添加相关配置即可 -->
<!-- spring4all的github上的源码地址https://github.com/SpringForAll/spring-boot-starter-swagger -->
<!-- 该项目的readme中介绍个各个参数的使用 -->
<!-- https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter -->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
server端-application.yml
Raw Copy
# 配置swagger
# swagger.enabled=是否启用swagger,默认:true
# swagger.title=标题
# swagger.description=描述
# swagger.version=版本
# swagger.license=许可证
# swagger.licenseUrl=许可证URL
# swagger.termsOfServiceUrl=服务条款URL
# swagger.contact.name=维护人
# swagger.contact.url=维护人URL
# swagger.contact.email=维护人email
# swagger.base-package=swagger扫描的基础包,默认:全扫描
# swagger.base-path=需要处理的基础URL规则,默认:/**
# swagger.exclude-path=需要排除的URL规则,默认:空
# swagger.host=文档的host信息,默认:空
# swagger.globalOperationParameters[0].name=参数名
# swagger.globalOperationParameters[0].description=描述信息
# swagger.globalOperationParameters[0].modelRef=指定参数类型
# swagger.globalOperationParameters[0].parameterType=指定参数存放位置,可选header,query,path,body.form
# swagger.globalOperationParameters[0].required=指定参数是否必传,true,false
swagger:
enabled: true
base-package: xin.admin
title: 管理后端平台
version: 1.0
description: 管理后端平台API
contact:
name: lixin
email: lixin_ma@outlook.com
#参数名
globalOperationParameters[0].name: Authorization
#描述信息
globalOperationParameters[0].description: 令牌
#指定参数类型
globalOperationParameters[0].modelRef: string
#指定参数存放位置,可选header,query,path,body.form
globalOperationParameters[0].parameterType: header
#指定参数是否必传,true,false
globalOperationParameters[0].required: false
server端-启动类.java
Raw Copy
package xin.admin;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableEurekaClient
@EnableCircuitBreaker
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("xin.admin.mapper")
@EnableSwagger2Doc
public class AdminBootstrap {
public static void main(String[] args) {
new SpringApplicationBuilder(AdminBootstrap.class).web(true).run(args); }
}
demo.md
Raw Copy

demo请点击,demo中使用的原生测swagger2

Comment list( 0 )

You need to Sign in for post a comment

Help Search