api 数据gzip压缩_如何使用GZip和Jersey压缩Java REST API中的响应
api 數據gzip壓縮
在某些情況下,您的REST api會提供非常長的響應,我們都知道移動設備/網絡上的傳輸速度和帶寬仍然非常重要。 我認為這是開發支持移動應用程序的REST api時需要解決的第一個性能優化點。 你猜怎么了? 因為響應是文本,所以我們可以壓縮它們。 借助當今智能手機和平板電腦的強大功能,在客戶端上解壓縮它們并不是什么大不了的事。因此,在本文中,我將介紹如何使用澤西島(Jersey)在Java中構建壓縮REST API響應的方法。是JAX-RS參考實現(以及更多)…
1.球衣過濾器和攔截器
好吧,得益于Jersey強大的過濾器和攔截器功能,實現起來相當容易。 過濾器主要用于操縱請求和響應參數,例如HTTP頭,URI和/或HTTP方法,而攔截器則用于通過操縱實體輸入/輸出流來操縱實體。
您已經在我的帖子中看到了過濾器的功能:
- 如何使用Jersey來在Java的服務器端添加CORS支持 ,在此我展示了如何CORS啟用REST API
和 - 如何使用SLF4J和Logback登錄Spring ,在那里我展示了如何記錄來自REST API的請求和響應
但要進行壓縮,將使用GZip WriterInterceptor 。 Writer攔截器用于將實體寫入“線路”的情況,在這種情況下,在服務器端,這意味著寫出響應實體時。
GZip作家攔截器
因此,讓我們看一下我們的GZip Writer攔截器:
GZip作家攔截器
package org.codingpedia.demo.rest.interceptors;import java.io.IOException; import java.io.OutputStream; import java.util.zip.GZIPOutputStream;import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext;@Provider @Compress public class GZIPWriterInterceptor implements WriterInterceptor {@Overridepublic void aroundWriteTo(WriterInterceptorContext context)throws IOException, WebApplicationException {MultivaluedMap<String,Object> headers = context.getHeaders();headers.add("Content-Encoding", "gzip");final OutputStream outputStream = context.getOutputStream();context.setOutputStream(new GZIPOutputStream(outputStream));context.proceed();} }注意:
- 它實現了WriterInterceptor ,它是消息正文WriterInterceptor器攔截器的接口,該攔截器包裝了對javax.ws.rs.ext.MessageBodyWriter.writeTo調用。
- 實現WriterInterceptor合同的提供程序必須在JAX-RS運行時中以編程方式注冊,或者必須使用@Provider批注進行注釋,以在提供程序掃描階段由JAX-RS運行時自動發現。
- @Compress是名稱綁定批注,我們將在下一段中對其進行詳細討論
- “攔截器從WriterInterceptorContext獲取輸出流,并設置一個新流,它是原始輸出流的GZIP包裝器。 執行完所有攔截器后,最后設置為WriterInterceptorContext的輸出流將用于實體的序列化。 在上面的示例中,實體字節將被寫入GZIPOutputStream,它將壓縮流數據并將其寫入原始輸出流。 原始流始終是將數據寫入“電線”的流。 在服務器上使用攔截器時,原始輸出流是將數據寫入底層服務器容器流的流,該流將響應發送到客戶端。 [2]
- “ WriteTo()的重寫方法將WriterInterceptorContext作為參數。 此上下文包含標頭參數,請求屬性,實體,實體流和其他屬性的獲取器和設置器。” [2]; 壓縮響應時,應將“ Content-Encoding”標頭設置為“ gzip”
壓縮注釋
過濾器和攔截器可以綁定名稱 。 名稱綁定是一個概念,它允許對JAX-RS運行時說,僅針對特定資源方法才執行特定過濾器或攔截器。 當過濾器或攔截器僅限于特定資源方法時,我們說它是名稱綁定的 。 沒有這種限制的過濾器和攔截器稱為global 。 在我們的案例中,我們構建了@Compress批注:
壓縮注釋
package org.codingpedia.demo.rest.interceptors;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 {}并用它來標記應該壓縮的資源上的方法( 例如,使用PodcastsResource獲取所有播PodcastsResource ):
@Compress資源方法上的注釋用法
@Component @Path("/podcasts") public class PodcastsResource {@Autowiredprivate PodcastService podcastService;.........................../** *********************************** READ ************************************//*** Returns all resources (podcasts) from the database* * @return* @throws IOException* @throws JsonMappingException* @throws JsonGenerationException* @throws AppException*/@GET@Compress@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })public List<Podcast> getPodcasts(@QueryParam("orderByInsertionDate") String orderByInsertionDate,@QueryParam("numberDaysToLookBack") Integer numberDaysToLookBack)throws IOException, AppException {List<Podcast> podcasts = podcastService.getPodcasts(orderByInsertionDate, numberDaysToLookBack);return podcasts;}........................... }2.測試
SOAPui
好吧,如果您正在使用SOAPui進行測試,則可以針對PodcastsResource發出以下請求。
請求:
請求示例
GET http://localhost:8888/demo-rest-jersey-spring/podcasts/?orderByInsertionDate=DESC HTTP/1.1 Accept-Encoding: gzip,deflate Accept: application/json, application/xml Host: localhost:8888 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5)響應:
GZipped json響應,由SOAPui自動解壓縮
HTTP/1.1 200 OK Content-Type: application/json Content-Encoding: gzip Content-Length: 409 Server: Jetty(9.0.7.v20131107)[{"id": 2,"title": "Quarks & Co - zum Mitnehmen","linkOnPodcastpedia": "http://www.podcastpedia.org/quarks","feed": "http://podcast.wdr.de/quarks.xml","description": "Quarks & Co: Das Wissenschaftsmagazin","insertionDate": "2014-10-29T10:46:13.00+0100"},{"id": 1,"title": "- The Naked Scientists Podcast - Stripping Down Science","linkOnPodcastpedia": "http://www.podcastpedia.org/podcasts/792/-The-Naked-Scientists-Podcast-Stripping-Down-Science","feed": "feed_placeholder","description": "The Naked Scientists flagship science show brings you a lighthearted look at the latest scientific breakthroughs, interviews with the world top scientists, answers to your science questions and science experiments to try at home.","insertionDate": "2014-10-29T10:46:02.00+0100"} ]SOAPui可以識別Content-Type: gzip標頭(已添加到GZIPWriterInterceptor并自動解壓縮響應并將其顯示為人眼可讀。
好,就是這樣。 您已經了解到Jersey如何直接壓縮REST api響應。
提示:如果您真的想學習如何在Java中設計和實現REST API,請閱讀以下教程–借助Jersey和Spring在Java中進行REST API設計和實現
翻譯自: https://www.javacodegeeks.com/2014/11/how-to-compress-responses-in-java-rest-api-with-gzip-and-jersey.html
api 數據gzip壓縮
總結
以上是生活随笔為你收集整理的api 数据gzip压缩_如何使用GZip和Jersey压缩Java REST API中的响应的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: openshift_在OpenShift
- 下一篇: Linux远程服务器文件拷贝到本地(li