Spring Cloud GateWay具有以下特性:
基于Spring Framework 5,Reactor和Spring Boot 2.0构建
动态路由:能够匹配任何请求属性
可以对路由指定Predicate(断言)和Filter(过滤器)
集成Hystrix的断路器功能
集成Spring Cloud 服务发现功能
易于编写的Predicate(断言)和Filter(过滤器)
请求限流功能
支持路径重写
动态路由配置:
server:
port: 9527
spring:
application:
name: cloud-gateway-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: payment_routh #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: lb://cloud-provider-service #匹配后提供服务的路由地址
predicates:
- Path=/payment/get/** #断言,路径相匹配的进行路由
- After=2021-03-18T10:21:27.610+08:00[Asia/Shanghai] #这个时间后才可以访问
#- Cookie=username,zzyy 要求带Cookie访问
#- Header=X-Request-Id, \d+ 请求头要有X-Request-Id属性并且值为整数的正则表达式
- id: payment_routh2
uri: lb://cloud-provider-service
predicates:
- Path=/payment/lb/**
eureka:
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://127.0.0.1:7001/eureka/
自定义过滤器:
在api网关创建一个类,这个类实现GlobalFilter, Ordered中的方法
package com.hj.cloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
/**
* @ClassName MyLogGateWayFilter
* @Deacription TODO
* @Author hj
* @Date 2021-3-18 15:31
**/
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("come in MyLogGateWayFilter"+new Date());
//请求时获取参数id
String id = exchange.getRequest().getQueryParams().getFirst("id");
//如果id为null,则不给进入
if(id == null){
log.info("id is null");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
//如果正常,则进入下一个过滤器
return chain.filter(exchange);
}
@Override
public int getOrder() {
//权重,数字越小优先级越高
return 0;
}
}