spring-cloud / spring-cloud-gateway

An API Gateway built on Spring Framework and Spring Boot providing routing and more.
http://cloud.spring.io
Apache License 2.0
4.51k stars 3.32k forks source link

Use AdaptCachedBodyGlobalFilter cache request body, routeId must add "ReactiveCompositeDiscoveryClient_" #3498

Open reesezxf opened 1 month ago

reesezxf commented 1 month ago

Describe the bug I want to use the AdaptCachedBodyGlobalFilter to cache all the post request body.

Here is my Config

@Configuration(proxyBeanMethods = false)
@Slf4j
public class EnableCachedBodyConfiguration {
    @Resource
    private ApplicationEventPublisher publisher;

    @Resource
    private GatewayProperties gatewayProperties;

    @PostConstruct
    public void init() {

        gatewayProperties.getRoutes().forEach(routeDefinition -> {
            System.out.println("route:::"+routeDefinition.getId()); // this value is like cms-service、order-service
            EnableBodyCachingEvent enableBodyCachingEvent = new EnableBodyCachingEvent(new Object(), routeDefinition.getId());
            publisher.publishEvent(enableBodyCachingEvent);
        });
    }
}

First this code doesn't work. Then I change the code to

EnableBodyCachingEvent enableBodyCachingEvent = new EnableBodyCachingEvent(new Object(), "ReactiveCompositeDiscoveryClient_" + routeDefinition.getId());

Now It works. The reason I add a pre str is I check the file: org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter, and I find this line

Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
// Here this route.getId is like  "ReactiveCompositeDiscoveryClient_cms-service"

if (body != null || !this.routesToCache.containsKey(route.getId())) {
    return chain.filter(exchange);
}
return ServerWebExchangeUtils.cacheRequestBody(exchange, (serverHttpRequest) -> {
    // don't mutate and build if same request object
    if (serverHttpRequest == exchange.getRequest()) {
        return chain.filter(exchange);
    }
    return chain.filter(exchange.mutate().request(serverHttpRequest).build());
});

So How did I use it wrong?

spencergibb commented 1 week ago

Can you provide your route configuration?

spring-cloud-issues commented 5 days ago

If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.