简体   繁体   中英

GZip compression of REST response

I am writing a REST service where I am sending a JSON response of size around 3MB. Application is developed using Scalatra Framework and running on Tomcat server. As data is big of size, I want to zip the content before sending over the network to browser client.

To compress the response, I have added below code in tomcat server.xml file:

<Connector port="8080" maxHttpHeaderSize="8192"
                maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
                enableLookups="false" redirectPort="8443" acceptCount="100"
                connectionTimeout="20000" disableUploadTimeout="true"
                compression="on"
                compressionMinSize="100"
                noCompressionUserAgents="gozilla, traviata"   compressableMimeType="text/html,text/xml,text/json,text/javascript,text/css,text/plain,                                   application/javascript,application/xml,application/xml+xhtml,application/json"/>

But I didn't find any different in the content transferred before and after adding the above configuration. It is adding content-encoding header Content-Encoding:gzip . It didn't solve my actual goal.

To test whether this configuration is really working or not, I have copied JSON file into server and tried to access that file. It is being received as small compressed file in the client side.

Seems I am missing some configuration to add to make HTTP JSON response as zipped one. Can someone help me to solve this problem?

I was able to solve this problem by using GzipFilter from ehcache-web dependency.

Added below dependencies in build.scala :

"org.slf4j" % "slf4j-jdk14" % "1.6.4",
 "net.sf.ehcache" % "ehcache-web" % "2.0.4",

Filter mapping in web.xml

 <filter>
        <filter-class>net.sf.ehcache.constructs.web.filter.GzipFilter</filter-class>
        <filter-name>GzipFilter</filter-name>
    </filter>
    <filter-mapping>
        <filter-name>GzipFilter</filter-name>
        <url-pattern>/rest/*</url-pattern>
    </filter-mapping>

Above code changes has solved my problem. Now response is compressed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM