gateway-断言-自定义断言

This commit is contained in:
bunny 2025-05-27 14:30:37 +08:00
parent 1c89bc4814
commit 5f04e0f16d
3 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,50 @@
package cn.bunny.gateway.predicates;
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
import java.util.List;
import java.util.function.Predicate;
@Component
public class VipRoutePredicateFactory extends AbstractRoutePredicateFactory<VipRoutePredicateFactory.Config> {
public VipRoutePredicateFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return List.of("param", "value");
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return (GatewayPredicate) serverWebExchange -> {
ServerHttpRequest request = serverWebExchange.getRequest();
String first = request.getQueryParams().getFirst(config.param);
return StringUtils.hasText(first) && first.equals(config.value);
};
}
@Getter
@Setter
@Validated
public static class Config {
@NotEmpty
private String param;
@NotEmpty
private String value;
}
}

View File

@ -13,5 +13,23 @@ spring:
args:
patterns: /api/product/**
matchTrailingSlash: true
- id: bing-route
uri: https://cn.bing.com/
predicates:
- name: Path
args:
patterns: /search
- name: Query
args:
param: q
regexp: 被世界温柔以待
# 短写法
# - Vip=User,bunny
# 长写法
- name: Vip
args:
param: user
value: bunny

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB