【问题标题】:Jersey, content gzip/deflate泽西岛,内容 gzip/deflate
【发布时间】:2013-09-26 05:13:21
【问题描述】:

我试图了解如何根据 Content-Encoding gzip|deflate 应用不同的拦截器并根据 Accept-Encoding 提供数据。我正在阅读 gzip/deflate 拦截器,但不太明白它是如何工作的。

public Response bigPayload( PayloadDto data ) {
   ...
   return Response.ok( BigDataDto ).build(); 
}

基本上我希望能够接受有效载荷 json 的 gzip/deflate 并在支持的情况下返回 gzip/deflate 数据。

谢谢。

【问题讨论】:

  • 是的,我看到了,它在哪里说明如何使它标头依赖,因此不同的拦截器可以附加到不同的内容,据我所知,该主题的文档并不完整,也不清晰。示例将起作用。

标签: jersey jersey-2.0


【解决方案1】:

要在服务器端使用 GZIP 和 Jersey,首先你应该实现 ReaderInterceptor 和 WriterInterceptor:

@Provider // This Annotation is IMPORTANT!
public class GZipInterceptor implements ReaderInterceptor, WriterInterceptor {
    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
        List<String> header = context.getHeaders().get("Content-Encoding");
        // decompress gzip stream only
        if (header != null && header.contains("gzip")) 
            context.setInputStream(new GZIPInputStream(context.getInputStream()));
        return context.proceed();
    }

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        context.setOutputStream(new GZIPOutputStream(context.getOutputStream()));
        context.getHeaders().add("Content-Encoding", "gzip");
        context.proceed();
    }
}

然后确保这个@Provider类在web.xml配置的自动扫描包/子包下:

<servlet>
    <servlet-name>Jersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>your.provider.package</param-value>
    </init-param>
</servlet>

如果你想按需使用 gzip 压缩,或许你可以使用 ThreadLocal 变量来寻求帮助,详情请查看我的帖子here

【讨论】:

  • 非常有用,谢谢。缺少一个右花括号来关闭 if 语句。
【解决方案2】:

当用户设置了标头Accept-Encoding: gzip, deflate 时,您希望从用户请求返回压缩响应,那么您需要在应用程序服务器中启用压缩。

在 Tomcat 中,您需要更改 &lt;TOMCAT_HOME&gt;/conf/server.xml,因为默认情况下压缩是关闭的。

    <Connector connectionTimeout="20000" 
            port="8080" protocol="HTTP/1.1" 
            redirectPort="8443" 
            compression="on"
            compressionMinSize="1"
            noCompressionUserAgents="gozilla, traviata"
            compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain"/>

请注意,您需要定义您希望应用服务器压缩的 compressableMimeType。

然后您可以使用 curl 进行测试....

未压缩的内容...

curl http://localhost:8080/your/url/too/data

压缩内容...

curl -H "Accept-Encoding: gzip, deflate" http://localhost:8080/your/url/too/data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2014-06-10
    • 2017-05-13
    • 2013-12-21
    相关资源
    最近更新 更多