Predicate 来自于 Java8 的接口。Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。
内置的一些断言如下图:
1基础配置
1.1使用springboot,导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
1.2启动类添加注解
package com.wn;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApp {
public static void main(String[] args) {
SpringApplication.run(GatewayApp.class, args);
}
}
1.3yml配置文件(根据自己的要求配置)
server:
port: 10010
spring:
application:
name: gateway-server
cloud:
gateway:
# 路由数组:指当请求满足什么样的断言时,转发到哪个服务上
routes:
# 路由标识,要求唯一,名称任意
- id: gateway-provider_1
# 请求最终被转发到的目标地址
uri: http://localhost:9024
# 设置断言
predicates:
# Path Route Predicate Factory 断言,满足 /gateway/provider/** 路径的请求都会被路由到 http://localhost:9024 这个uri中
- Path=/gateway/provider/**
# Weight Route Predicate Factory 断言,同一分组按照权重进行分配流量,这里分配了80%
# 第一个group1是分组名,第二个参数是权重
- Weight=group1, 8
# 配置过滤器(局部)
filters:
# StripPrefix:去除原始请求路径中的前1级路径,即/gateway
- StripPrefix=1
- id: gateway-provider_2
uri: http://localhost:9025
# 设置断言
predicates:
- Path=/gateway/provider/**
# Weight Route Predicate Factory,同一分组按照权重进行分配流量,这里分配了20%
- Weight=group1, 2
# 配置过滤器(局部)
filters:
# StripPrefix:去除原始请求路径中的前1级路径,即/gateway
- StripPrefix=1
2.The Path Route Predicate Factory
server:
port: 10010
spring:
application:
name: gateway-server
cloud:
gateway:
routes:
- id: consumer-server
uri: lb://consumer-server
predicates:
- Path=/consumer/**
filters:
- StripPrefix= 1
测试:
添加consumer路徑---->成功
不添加路径----->失败
2.The After Route Predicate Factory
routes:
- id: after_route
uri: lb://consumer-server
predicates:
Before=2023-07-16T22:34:47.789+08:00[Asia/Shanghai]
测试
日期之前---->成功
日期之后---->失败