feat(gateway): 自定义路由

This commit is contained in:
Bunny 2025-02-10 22:19:27 +08:00
parent a66ce7abbf
commit 7a14264bb5
4 changed files with 66 additions and 0 deletions

View File

@ -18,6 +18,11 @@
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>annotationProcessor</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>

View File

@ -0,0 +1,54 @@
package cn.bunny.config;
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.Arrays;
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 Arrays.asList("param", "value");
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return (GatewayPredicate) serverWebExchange -> {
ServerHttpRequest request = serverWebExchange.getRequest();
String first = request.getQueryParams().getFirst(config.getParam());
return StringUtils.hasText(first) && first.equals(config.getValue());
};
}
/**
* 可以配置的参数
*/
@Getter
@Setter
@Validated
public static class Config {
@NotEmpty
private String param;
@NotEmpty
private String value;
}
}

View File

@ -12,7 +12,13 @@ spring:
args:
param: wd
regexp: .*
# 从这个往上只要http://localhost:8800/s?wd=49 即可通过
- name: Vip # 名称为 Vip RoutePredicateFactory
args:
param: user
value: bunny
# 从这个往上http://localhost:8800/s?wd=49&user=bunny
- id: service-cloud1
uri: lb://service-cloud1
predicates:

View File

@ -35,6 +35,7 @@ spring:
transport:
dashboard: 192.168.3.132:8858
eager: true # 项目启动就连接
feign:
sentinel:
enabled: true