springcloud-gateway构建
1.创建springboot项目,依赖gateway。注意由于gateway依赖的是webflux,不可依赖springMVC
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
2.编写yml配置文件
spring: cloud: gateway: httpclient: #连接超时 connect-timeout: #响应超时 response-timeout: 10s globalcors: cors-configurations: '[/**]': #允许跨域的源 allowedOrigins: - "https://usercenter.test.com" - "https://business.test.com" #允许跨域的方法 allowedMethods: - GET - POST - PUT - PATCH - DELETE - OPTIONS #允许跨域header里的字段 allowedHeaders: - Content-Type - Authorization - istoken #过滤器 default-filters: #使用断路器 - name: CircuitBreaker args: #使用断路器的名称 name: breakage #使用自定义过滤器(放行指定路径,解析token) - name: AuthorizationValidation args: excludePaths: /v?/auth/login,/v?/auth/refresh,/captchaImage decodeKey: xxxxxxxxxx #使用自定义过滤器,参数逗号隔开(鉴权) - AccessControl=UC:PERMIT:ACCESS,UC:ACCESS:USER:%s,true #使用内置过滤器(跨域可能产生重复的响应头,去重并保留第一个) - DedupeResponseHeader=Vary Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_FIRST #路由器 routes: - id: usercenter-route #路由路径,使用eureka时以 lb://应用名 指定 uri: lb://usercenter #拦截路径 predicates: - Path=/user/v*/** #去掉Path中前n个节点 filters: - StripPrefix=1 - id: business-route uri: lb://business predicates: - Path=/business/** filters: - StripPrefix=1 #redis配置 redis: host: localhost port: 6379 password: SDXTYksjQ database: 5 connect-timeout: 2s server: port: 8085 #日志 logging: level: root: info com: toaind: cloud: gateway: debug #断路器 resilience4j: circuitbreaker: configs: default: #健康监测 registerHealthIndicator: true #状态收集器大小:close状态时,收集多少请求状态用于计算失败率。TIME_BASED时为秒数,COUNT_BASED时为次数 slidingWindowSize: 50 #最小请求次数:达到该次数才会计算失败率 minimumNumberOfCalls: 30 #状态收集器类型:TIME_BASED根据时间计算,COUNT_BASED根据次数计算 slidingWindowType: TIME_BASED #半开状态允许调用的次数 permittedNumberOfCallsInHalfOpenState: 10 #不需要调用即可触发从打开到半打开状态 automaticTransitionFromOpenToHalfOpenEnabled: true #从打开到半开的等待时间 waitDurationInOpenState: 5s #失败率阈值:百分比 failureRateThreshold: 50 #用于计算失败率的异常 recordExceptions: - org.springframework.web.client.HttpServerErrorException instances: #断路器实例名称 breakage: #断路器实例使用的配置名称 baseConfig: default
3.实现自定义过滤器
自定义过滤器有以下两种方式创建:
3.1配置全局自定义过滤器
Filtering Web Handler会加载所有注册到sping的GlobalFilter的实例。
@Bean @Order(-1) public GlobalFilter a() { return (exchange, chain) -> { log.info("first pre filter"); return chain.filter(exchange).then(Mono.fromRunnable(() -> { log.info("last post filter"); })); }; }
3.2继承AbstractGatewayFilterFactory配置过滤器工厂,在yml中指定使用位置。如果以GatewayFilterFactory类名结尾,配置时可不写。
@Component
public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
public PreGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
// grab configuration from Config object
return (exchange, chain) -> {
//change.filter前过滤
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
ServerHttpRequest request =builder.build();
return chain.filter(exchange.mutate().request(request).build());
};
}
public static class Config {
//yml传入的配置属性
}
}