网关(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对象
  • 从而获取到请求的参数、请求方式、请求头等信息
相关推荐
咖啡Beans10 小时前
使用OpenFeign实现微服务间通信
java·spring cloud
咖啡Beans2 天前
SpringCloud网关Gateway功能实现
java·spring cloud
麦兜*3 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
熙客3 天前
SpringCloud概述
java·spring cloud·微服务
一又四分之一.3 天前
spring、springboot、springCloud
spring boot·spring·spring cloud
疯狂的维修4 天前
关于Gateway configration studio软件配置网关
网络协议·c#·自动化·gateway
hadage2334 天前
--- 统一请求入口 Gateway ---
gateway
lllsure5 天前
【Docker】镜像
java·spring cloud·docker
波波烤鸭5 天前
深入理解 Gateway 网关:原理、源码解析与最佳实践
java·spring·gateway
DO_Community5 天前
DigitalOcean Kubernetes 现已支持 Gateway API 托管服务
容器·kubernetes·gateway