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 注解可以用在方法上,也可以用在类内每个方法的资源类上。