admin管理员组

文章数量:1125883

I'm trying to return a response in my gateway depend on values if found in redis without hitting the controller by but it always hit the controller and while returning the NettyRoutingFilter tries to remove a Header and then it throws UnsupportedOperationException since that the response is already commited

@Override
 public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String api = apis.keySet().stream()
                .filter(e -> request.getURI().getPath().endsWith(e))
                .findFirst()
                .orElse(null);

        if (api == null) {
            return chain.filter(exchange);
        }


        return ReactiveSecurityContextHolder.getContext()
                .flatMap(sc -> {
                    try {
                        Authentication authentication = sc.getAuthentication();

                        if (authentication == null || authentication.getPrincipal() == null) {
                            return chain.filter(exchange);
                        }

                        Set<String> urlKey = generateCacheKey(request, apis.get(api));

                        List<Object> cachedResponse = redisTemplate.opsForValue().multiGet(urlKey);

                        if (cachedResponse != null && !cachedResponse.isEmpty()) {
                            return writeCachedResponse(response, cachedResponse.get(0).toString());
                        } else {
                            return chain.filter(exchange);
                        }
                    } catch (Exception e) {
                        return Mono.error(e);
                    }
                })
                .switchIfEmpty(Mono.defer(() -> {
                    return chain.filter(exchange);
                }))
                .doOnError(e -> log.error("Error during filter execution", e));
    }

    private Set<String> generateCacheKey(ServerHttpRequest request, String cacheKey) {
        return redisTemplate.keys("*" + cacheKey + "*");
    }

    private Mono<Void> writeCachedResponse(ServerHttpResponse response, String cachedResponse) {
        return response.writeWith(Mono.just(response.bufferFactory().wrap(cachedResponse.getBytes())));
    }

expects to terminate the chain and returns the response directly

本文标签: