接口返回大数据量压缩,通过注解自定义指定接口是否进行压缩

1.修改拦截器类 GzipResponseInterceptor,只有当请求的方法上标有 @EnableGzipCompression 注解时,才进行压缩处理。

package com.htht.config;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.zip.GZIPOutputStream;

/**
 * @projectName: meteovis
 * @package: com.htht.config
 * @className: GzipResponseInterceptor
 * @author: MCP
 * @description: TODO
 * @date: 2024/2/23 16:35
 */
@Component
public class GzipResponseInterceptor implements HandlerInterceptor {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        // 检查方法上是否标有 @EnableGzipCompression 注解
        Method handlerMethod = ((HandlerMethod) handler).getMethod();
        if (handlerMethod.isAnnotationPresent(EnableGzipCompression.class)) {
            // 进行数据压缩处理
            if (response.getContentType() != null && response.getContentType().equals("application/json")) {
                String oldBody = response.toString();
                byte[] compressedBody = gzipCompress(oldBody);
                response.setContentLength(compressedBody.length);
                response.setHeader("Content-Encoding", "gzip");
                response.getOutputStream().write(compressedBody);
            }
        }
    }

    private byte[] gzipCompress(String str) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos);
            gzipOutputStream.write(str.getBytes());
            gzipOutputStream.close();
            return baos.toByteArray();
        } catch (IOException e) {
            // Handle exception
            e.printStackTrace();
            return new byte[0];
        }
    }

}

2.自定义注解

package com.htht.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @projectName: meteovis
 * @package: com.htht.config
 * @className: EnableGzipCompression
 * @author: MCP
 * @description: TODO
 * @date: 2024/2/23 16:45
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableGzipCompression {
}





3.使用实例:添加 @EnableGzipCompression即可

@RequestMapping(value = "/firstData/{time}/", method = RequestMethod.GET)
    @ApiOperation(value = "获取地面全要素最新一条数据", httpMethod = "GET")
    @EnableGzipCompression
    public  ResponseEntity getSurfFirstDataByTime(@PathVariable("time") String time, boolean isHandleP) {
        FeatureJson surfFirstDataByTime = surfService.getSurfFirstDataByTime(time, isHandleP);
        // 压缩 JSON 数据
        byte[] compressedData = gzipCompress(JSON.toJSONString(surfFirstDataByTime));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentLength(compressedData.length);
        headers.set("Content-Encoding", "gzip");
        return new ResponseEntity<>(compressedData, headers, HttpStatus.OK);
    }

4.压缩方法

    private byte[] gzipCompress(String str) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos);
            gzipOutputStream.write(str.getBytes());
            gzipOutputStream.close();
            return baos.toByteArray();
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
            return new byte[0];
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值