gateway 返回Body 数据居然出现偶现的乱码问题, 原来是数据被截断背的锅

1、查看问题

在开发的时候,发现页面的数据偶先乱码,但有不清楚是那的问题,我们使用swagger-ui参数,发现乱码数据,但概率为1/10,每10次大概查询一次,如下
在这里插入图片描述
一会又是正常的
在这里插入图片描述
返回数据是json数据,编码 utf8,一切都是正常的,重点是偶现,这就奇葩了
在这里插入图片描述

2、定位问题

因为我们是微服务项目使用了 spring-cloud-gateway做为网关,于是使用网关地址和 项目地址分别测试

走网关地址
在这里插入图片描述
走具体的项目地址
在这里插入图片描述
果然走网关地址的url 会出现乱码,走具体的项目地址的不会出现乱码问题
与是就想到了是不是返回参数被截断了,中文字符是2-3个字节,返回的参数太多,gateway会分段处理数据
当前代码如下:----> 不知道大家能不能看出来有什么问题


    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private  GatewayLogConfig gatewayLogConfig;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    Mono<Void> voidMono = super.writeWith(fluxBody.map(dataBuffer -> {
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        //释放掉内存
                        DataBufferUtils.release(dataBuffer);
                        //原数据,想修改、查看就随意而为了
                        String data = new String(content, Charset.forName("UTF-8"));
                        // 不对html 页面进行过滤
                        // if (data.indexOf("<html>") == -1) {   // }
                        //xss过滤
                        if (authProperties.isXssRespAttack()) {
                            data = HtmlEncodeUtil.htmlEncode(data);
                        }
                        //byte[] uppedContent = new String(data, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(data.getBytes());
                    }));
                    // 打印日志, 注意,body数据在exchange 只能读取一次
                    gatewayLogConfig.putLog(exchange, "响应成功");
                    return voidMono;
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
        // replace response with decorator
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }
这个方法如果数据过多太长 super.writeWith(fluxBody.map(dataBuffer -> { 会多次进入,数据会被拆成字节在拼接在一起返回前端,中文是2到3字节,如果刚好把这个中文的拆成两半,一个字的上半部分字节在第一次,下半部分字节在第二次,这样返回的数据在拼接在一起被拆了的字节无法还原成一个中文汉字,就会出现乱码的问题了 
3、处理问题
  • 乱码问题其实就是返回数据gateway 进行了截断所产生的,所以我们需要把返回的组进行join上就不会产生乱码的,如果还是乱码,请根据自己系统的实际编码进行转换即可完美解决,

  • 请注意:这里使用的是 DefaultDataBufferFactory 的join方法去合并多个dataBuffers ↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 最大的区别

修改代码如下,重点部分

 super.writeWith(fluxBody.buffer().map(dataBuffers -> {
      DataBuffer join = dataBufferFactory.join(dataBuffers);
       byte[] content = new byte[join.readableByteCount()];
       join.read(content);
       DataBufferUtils.release(join);
       String responseData = new String(content, Charsets.UTF_8);

当前完整代码如下

    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private GatewayLogConfig gatewayLogConfig;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    if (body instanceof Flux) {
                        Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                            DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                            DataBuffer join = dataBufferFactory.join(dataBuffers);
                            byte[] content = new byte[join.readableByteCount()];
                            join.read(content);
                            DataBufferUtils.release(join);
                            String responseData = new String(content, Charsets.UTF_8);
                            if (log.isDebugEnabled()) {
                                log.debug("响应转前:{}", responseData);
                            }
                            responseData = responseData.replaceAll(":null", ":\"\"");
                            if (log.isDebugEnabled()) {
                                log.debug("响应转后:{}", responseData);
                            }
                            byte[] uppedContent = responseData.getBytes(Charsets.UTF_8);
                            // 不对html 页面进行过滤
                            // if (data.indexOf("<html>") == -1) {   // }
                            // 判断是否为swagger文档,v2/api-docs  ,是不进行xss过滤
                            if (responseData.toString().indexOf("v2/api-docs") == -1 && authProperties.isXssRespAttack()) {
                                responseData = HtmlEncodeUtil.htmlEncode(responseData);
                            }
                            // 注意,body数据在exchange 只能读取一次
                            gatewayLogConfig.putLog(exchange, "响应成功");
                            return bufferFactory.wrap(uppedContent);
                        }));
                    } else {
                        return chain.filter(exchange);
                    }
                }
            };
            // replace response with decorator
            return chain.filter(exchange.mutate().response(decoratedResponse).build());
        } catch (Exception e) {
            log.error(" ReplaceNullFilter 异常", e);
            return chain.filter(exchange);
        }
    }
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值