我在JAX-RS端点中发送大量数据作为JSON响应。
有没有办法在 javax.ws.rs 中设置"始终压缩"参数作为端点的注释或在 payara-micro 级别设置参数作为参数,以始终压缩响应?
当前状态是端点支持未压缩和压缩(例如 curl --压缩)提供数据的方式。
@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)进行响应。
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() {
}
您可以通过设置级别来调整 GatewayGZIP 中的压缩级别。我使用最小值以获得最佳速度。 @Compress注释可用于方法或类内每个方法的资源类。