1

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

有没有办法将 javax.ws.rs 中的“always-compress”参数设置为端点的注释或在 payara-micro 级别作为参数,以始终压缩响应?

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

@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() {

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

4

1 回答 1

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 来调整 GatewayGZIPOutputStreamobject 中的压缩级别。我正在使用最低速度以获得最佳速度。@Compress 注解可以用在方法上,也可以用在类内每个方法的资源类上。

于 2020-11-07T10:46:57.090 回答