网关(Gateway)- 自定义断言工厂

自定义断言工厂类

DemoRoutePredicateFactory

java 复制代码
package com.learning.springcloud.custom;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

 @Component
public class DemoRoutePredicateFactory extends AbstractRoutePredicateFactory<DemoRoutePredicateFactory.Config> {


    public DemoRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            public boolean test(ServerWebExchange exchange) {
                if ("YES".equals(config.getName())) {
                    return true;
                }
                return false;
            }
        };
    }

    // 和 内部类 config的相互对应 返回对应的配置信息
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name");
    }


    // 用于接收 配置文件中的断言信息
    @Validated
    public static class Config {

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

路由配置说明

    • Demo=YES
java 复制代码
server:
  port: 8088
spring:
  application:
    name: api-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8847
        username: nacos
        password: nacos
    gateway:
      routes:
        - id: order_route # 路由唯一标识
          #uri: http://localhost:8020 # 需要转发的地址
          uri: lb://order-service # 需要转发的地址
          # 断言规则  用于路由规则的匹配
          predicates:
            - Demo=YES
          filters:
            - StripPrefix=1 # 转发去掉第一层路径
            # http://localhost:8020/order-serv/order/add => http://localhost:8020/order/add

访问效果

    • Demo=YES
    • Demo=NO

实现说明

  • 命名必须需要以 RoutePredicateFactory 结尾
  • 继承 AbstractRoutePredicateFactory 类
  • 必须为spring的组件bean(@Component)
  • 必须要有内部类 Config 以及 对应的 shortcutFieldOrder 方法
  • 重写 apply 方法的逻辑
  • 可通过 exchange.getRequest() 获取到ServerHttpRequest对象
  • 从而获取到请求的参数、请求方式、请求头等信息
相关推荐
万物皆字节1 天前
spring cloud负载均衡之FeignBlockingLoadBalancerClient、BlockingLoadBalancerClient
spring cloud
Ken_11151 天前
SpringCloud系列(49)--SpringCloud Stream消息驱动之实现生产者
spring cloud
guojl1 天前
Ribbon原理和源码分析
spring cloud·微服务
guojl2 天前
RestTemplate使用手册
spring cloud·微服务
guojl2 天前
RestTemplate原理分析
spring cloud·微服务
Ken_11152 天前
SpringCloud系列(51)--SpringCloud Stream之使用分组解决消息重复消费问题
spring cloud
lwb_01182 天前
SpringCloud——Gateway新一代网关
spring·spring cloud·gateway
你是人间五月天2 天前
gateway断言配置详解
gateway
weixin_387545642 天前
深入解析 AI Gateway:新一代智能流量控制中枢
人工智能·gateway
述雾学java2 天前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel