如何在JAX-RS端点/ payara-micro响应中强制执行gzip压缩

时间:2019-05-28 10:49:43

标签: jersey compression gzip payara-micro

我正在 JAX-RS 端点中作为 JSON 响应发送大量数据。

是否可以将javax.ws.rs中的“始终压缩”参数设置为对端点的注释或在payara-micro级别上作为参数,以始终压缩响应?

>

当前状态是端点支持提供数据的未压缩压缩(例如,curl-压缩)方式。

input {
  visibility: hidden;
}
input:before {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #CCC;
  visibility: visible;
}

input:checked:before {
  background-color: blue;
}

我希望端点将始终以压缩数据进行响应(内容编码:gzip)。

1 个答案:

答案 0 :(得分:1)

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

import javax.ws.rs.NameBinding;

//@Compress annotation is the name binding annotation
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Compress {
}

拦截器

import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;

import javax.enterprise.context.Dependent;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;

import hr.abc.leonus.api.gateway.util.Compress;

@Provider
@Compress
public class GZIPWriterInterceptor implements WriterInterceptor {

    public static final String CONTENT_ENCODING = "Content-Encoding";
    public static final String GZIP = "gzip";

    @Override
    public void aroundWriteTo(WriterInterceptorContext context)
            throws IOException, WebApplicationException {

        MultivaluedMap<String, Object> headers = context.getHeaders();
        headers.add(CONTENT_ENCODING, GZIP);

        final OutputStream outputStream = context.getOutputStream();

        GatewayGZIPOutputStream gzipStream = new GatewayGZIPOutputStream(outputStream);
        gzipStream.setLevel(Deflater.BEST_SPEED);
        context.setOutputStream(gzipStream);
        context.proceed();
    }
}

class GatewayGZIPOutputStreamextends GZIPOutputStream {

    public GatewayGZIPOutputStream(OutputStream out) throws IOException {
        super(out);
    }

    public void setLevel(int level) {
        def.setLevel(level);
    }
}

在端点上的用法

@Compress
@GET
@Path("/big-response")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Provides Json information about some etities")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Transfer successful"),
        @ApiResponse(code = 400, message = "Bad request"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void retrieveTheData() {
}

您可以通过设置level来调整GatewayGZIPOutputStream对象中的压缩级别。我正在使用最低速度以获得最佳速度。 对于类内的每个方法,@Compress批注可用于方法或资源类。