首页 > 其他分享 >springcloud gateway filter 重写response

springcloud gateway filter 重写response

时间:2023-04-28 14:45:27浏览次数:40  
标签:return exchange springcloud springframework filter import org gateway

 

import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Locale;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR;

@Component
public class GlobalGatewayFilter implements GlobalFilter, Ordered {

    private final List<HttpMessageReader<?>> messageReaders;

    public GlobalGatewayFilter(ServerCodecConfigurer serverCodecConfigurer) {
        this.messageReaders = serverCodecConfigurer.getReaders();
    }

    @Autowired
    private MessageSource messageSource;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String language = request.getQueryParams().getFirst("lang");
        Locale locale = LocaleContextHolder.getLocale();
        if (language != null && language.length() > 0) {
            String[] split = language.split("_");
            locale = new Locale(split[0], split[1]);
        }
        LocaleContextHolder.setLocaleContext(new SimpleLocaleContext(locale), true);

            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(exchange.getResponse()) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    String originalResponseContentType = exchange.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);
                    if (originalResponseContentType.startsWith("application/json")){
                        ClientResponse clientResponse = ClientResponse
                                .create(this.getDelegate().getStatusCode(), messageReaders)
                                .body(Flux.from(body)).build();

                        Mono<String> bodyMono = clientResponse.bodyToMono(String.class).map((respBody) -> {
                            System.out.println(respBody);
                            Locale locale = LocaleContextHolder.getLocale();
                            try {
                                String s = messageSource.getMessage( "", null, locale);
                            }catch (NoSuchMessageException e){
                                e.printStackTrace();
                                return respBody;
                            }
                            return respBody;
                        });

                        BodyInserter<Mono<String>, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromPublisher(bodyMono,
                                String.class);
                        CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
                                exchange, exchange.getResponse().getHeaders());
                        return bodyInserter.insert(outputMessage, new BodyInserterContext())
                                .then(Mono.defer(() -> {
                                    Flux<DataBuffer> messageBody = outputMessage.getBody();
                                    HttpHeaders headers = getDelegate().getHeaders();
                                    if (!headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
                                        messageBody = messageBody.doOnNext(data -> headers
                                                .setContentLength(data.readableByteCount()));
                                    }
                                    // TODO: fail if isStreamingMediaType?
                                    return getDelegate().writeWith(messageBody);
                                }));
                    }else {
                        return super.writeWith(body);
                    }

                }
            };
            return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }


    @Override
    public int getOrder() {
        return -1;
    }

}

 

标签:return,exchange,springcloud,springframework,filter,import,org,gateway
From: https://www.cnblogs.com/dongma/p/17362175.html

相关文章

  • gateway 异常
    ClassNotFoundException:javax.validation.ValidationException 三、问题nestedexceptionisjava.lang.NoClassDefFoundError:javax/validation/ValidationException原因:项目中没有引用 spring-boot-starter-validation包Asof#19550,WebandWebFluxstartersd......
  • TypeError: Cannot read properties of undefined (reading 'filter')
    TypeError:Cannotreadpropertiesofundefined(reading'filter')constfilterTableData=computed(()=>store.data.users!.filter((data)=>!search.value||data.nick.toLowerCase().includes(search.value......
  • SpringCloud微服务架构分析说明!
    SpringCloud是一个基于SpringBoot的微服务框架,它提供了一系列的工具和组件,用于构建分布式系统中各个微服务之间的通信和互联,实现服务发现、负载均衡、分布式配置等功能。下面我们来具体解析一下SpringCloud微服务架构。服务注册与发现在微服务架构中,服务的数量非常多,因此需要一个机......
  • 小团队真的适合引入SpringCloud微服务吗?
    单体应用时代接口定义持续集成(CI)微服务时代服务拆分原则框架选择架构改造自动化部署链路跟踪运维监控容器化时代架构改造SpringCloud与k8s的融合CI的改造小结微服务是否适合小团队是个见仁见智的问题。回归现象看本质,随着业务......
  • servlet、filter 顺序
    java代码:packagecom.servlet;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassHelloServlet......
  • springcloud OpenFeign的使用
    在这里只记录OpenFeign关键的使用步骤,A、B两个项目是基于springboot、springcloud实现的,并且在nacos中有服务注册。第一步:导入依赖<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</a......
  • PYTHON FILTER
    Filter顾名思义,filter过滤列表中的元素,并且返回一个由所有符合要求的元素所构成的列表,符合要求即函数映射到该元素时返回值为True.这里是一个简短的例子:number_list=range(-5,5)less_than_zero=filter(lambdax:x<0,number_list)print(list(less_than_zero))#......
  • How use the RegExp to filter IP address in js All In One
    HowusetheRegExptofilterIPaddressinjsAllInOne如何使用RegExp在js中过滤IP地址192.168.18.1<192.168.18.N<192.168.18.255ignoreIPs:192.168.18.0/192.168.18.1/192.168.18.255errorfunctiontest(n){letreg=/192\.168\.(1?[0-9][0-......
  • Filter概述及快速入门
    Filter概述及快速入门Filter概述:概念:Filter表示过滤器,是JavaWeb三大组件之一JavaWeb三大组件:Servlet,Filter,Listener过滤器可以把对资源的请求拦截下来,从而实现一些特殊的功能过滤器一般完成一些通用的操作:比如:权限控制,统一编码处理,敏感字符处理等......
  • SpringCloud 微服务 负载均衡问题 坑死老子了!(铁大软工刘雪丰)
    fetch-registry:true是默认的,刚开始学,你会发现虽然能运行,但是会抛异常,所以我就改成false了。改为false确实不抛异常。但是!!!,如果用负载均衡改进代码,就必须设为true,因为它会报错:Noinstancesavailablefor...,连运行都运行不了。我在网上找了很久,防火墙,依赖重复,依赖版本等方法我都试......