gateway-自定义过滤器工厂

This commit is contained in:
bunny 2025-05-27 16:32:00 +08:00
parent 93b919be6a
commit 27e94f17e1
3 changed files with 39 additions and 0 deletions

View File

@ -0,0 +1,38 @@
package cn.bunny.gateway.filter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.util.UUID;
@Component
public class OnceTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
@Override
public GatewayFilter apply(NameValueConfig config) {
// 每次相应之前添加一次性令牌
return (exchange, chain) -> chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
HttpHeaders headers = response.getHeaders();
String name = config.getName();
String value = config.getValue();
if ("uuid".equalsIgnoreCase(value)) {
value = UUID.randomUUID().toString();
}
if ("jwt".equalsIgnoreCase(value)) {
value = "JWT的token";
}
headers.add(name, value);
}));
}
}

View File

@ -8,6 +8,7 @@ spring:
- Path=/api/order/**
filters:
- AddRequestHeader=X-Request-red, blue
- OnceToken=X-Response-Token, uuid
- id: product-route
uri: lb://service-product

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB