设为首页 加入收藏

TOP

Spring Cloud Gateway:新一代微服务 API 网关,用起来真优雅!(二)
2023-09-23 15:44:43 】 浏览:272
Tags:Spring Cloud Gateway API 网关
# 断言,路径相匹配的条件 predicates: - Path=/routeconfig/rest/**

此时,当id为config_route的路由规则匹配某个请求后,在调用该请求对应的服务时,就会从nacos注册中心自动发现服务,并在服务调用的时候实现负载均衡。

8.Predicate

在Gateway中,有一些的内置Predicate Factory,有了这些Pridicate Factory,在运行时,Gateway会 自动根据需要创建其对应的Pridicate对象测试路由条件。

Path 路由断言 Factory: 根据请求路径匹配的路由条件工厂

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        # 如果可以匹配的PathPattern有多个,则每个路径模式以,分开
        - Path=/red/{segment},/blue/{segment}

After 路由断言 Factory: 在指定日期时间之后发生的请求都将被匹配

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]

Cookie 路由断言 Factory: Cookie 路由断言 Factory有两个参数,cookie名称和正则表达式。请求包含此cookie名称且正则表达式为真的将会被匹配。

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p

Header 路由断言 Factory: Header 路由断言 Factory有两个参数,header名称和正则表达式。请求包含此header名称且正则表达式为真的将会被匹配。

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+

Host 路由断言 Factory: Host 路由断言 Factory包括一个参数:host name列表。使用Ant路径匹配规则, . 作为分隔符。

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org

Method 路由断言 Factory: Method 路由断言 Factory只包含一个参数:需要匹配的HTTP请求方式

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET

自定义Predicate

可以自定义Predicate来实现复杂的路由匹配规则:

// 实现自定义 Predicate 工厂
// 通过HostRoutePredicateFactory创建Predicate进行路由判断
@Component
public class MyHostRoutePredicateFactory extends AbstractRoutePredicateFactory<MyHostRoutePredicateFactory.Config> {

  public MyHostRoutePredicateFactory() {
      // Config 类作为 Predicate 的配置参数类
      super(Config.class);
  }

  public static class Config {
      // 路由匹配规则
      private String hostName;

      public String getHostName() {
        return hostName;
      }

      public void setHostName(String hostName) {
        this.hostName = hostName; 
      }
  }

  // 生成一个 Predicate 实例
  @Override
  public Predicate<ServerWebExchange> apply(Config config) {
      // 实现匹配逻辑
      return exchange -> {
          // 根据config实现匹配判断
          
          String host = exchange.getRequest().getURI().getHost();
          // 匹配配置中的域名
          return host.equals(config.getHostName());
      };
  } 

}

// 使用
RouteLocator locator = new RouteLocatorBuilder(router)
  .routes()
  .route("test_route", r -> r.path("/test")
  .filters(f -> f.filter(new MyHostRoutePredicateFactory.Config("www.test.com")))
  .uri("http://localhost:8080"))
  .build();

9.自定义Filter

可以通过实现GatewayFilter和Ordered接口自定义Filter来实现请求处理逻辑:

@Component
public class TokenFilter implements GatewayFilter, Ordered {

   @Override
   public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
      //请求处理逻辑
      log.info("请求路径:"+ exchange.getRequest().getPath());
      
      ServerHttpRequest request = exchange.getRequest();
   MultiValueMap<String, HttpCookie> cookies = request.getCookies();
   List<HttpCookie> tokens = cookies.get("access_token");
   if (tokens == null || tokens.size() == 0) {
      throw new RuntimeException("少了cookie!");
   }
      
      return chain.filter(exchange);
   }

   @Override
   public int getOrder() {
      return 0; 
首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇记一次 Redisson 线上问题 → ERR.. 下一篇SpringBoot集成微信支付JSAPIV3保..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目