<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 使用 ETag 的 RESTEasy 緩存控制示例 > 原文: [https://howtodoinjava.com/resteasy/jax-rs-resteasy-cache-control-with-etag-example/](https://howtodoinjava.com/resteasy/jax-rs-resteasy-cache-control-with-etag-example/) [**ETags**](https://en.wikipedia.org/wiki/HTTP_ETag "etag") 或實體標簽是很有用的 [**HTTP 標頭**](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields "HTTP header"),它們可以通過最小化系統上的服務器負載來幫助構建超快速的應用。 ETag 設置為對客戶端的響應,因此客戶端可以對條件請求使用各種控制請求標頭,例如`If-Match`和`If-None-Match`。[`javax.ws.rs.core.Response.ResponseBuilder#tag()`](https://docs.oracle.com/javaee/6/api/javax/ws/rs/core/Response.ResponseBuilder.html#tag%28javax.ws.rs.core.EntityTag%29 "ResponseBuilder")和[`javax.ws.rs.core.EntityTag`](https://docs.oracle.com/javaee/6/api/javax/ws/rs/core/EntityTag.html "EntityTag")是用于 ETag 的實用類。 在服務器端,不變的 ETag(HTTP 請求附帶的 ETag 與為請求的資源計算的 ETag 之間的匹配)只是意味著,資源與上次請求時間相比沒有變化,因此只需發送 HTTP 304 標頭[未修改]就足夠了, 客戶端可以使用本地可用的資源副本而不必擔心。 為了演示該示例,我在服務類中有兩個 REST API。 **a)GET `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1`** 此 API 將獲取用戶資源,該資源將附加有 ETag。 服務器將使用此 ETag 來驗證用戶詳細信息是否已在上次請求中更新。 **b)PUT `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1`** 此 API 將對服務器上的用戶資源進行一些更新,這將強制服務器再次返回新的資源副本。 讓我們逐步構建示例。 ## 步驟 1)使用 maven 創建一個新的 Java Web 項目并添加以下依賴項。 ```java <repositories> <repository> <id>jboss</id> <url>http://repository.jboss.org/maven2</url> </repository> </repositories> <dependencies> <!-- core library --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>2.3.1.GA</version> </dependency> <!-- JAXB support --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxb-provider</artifactId> <version>2.3.1.GA</version> </dependency> <dependency> <groupId>net.sf.scannotation</groupId> <artifactId>scannotation</artifactId> <version>1.0.2</version> </dependency> </dependencies> ``` ## 步驟 2)制作一個類來表示用戶資源 確保提供一些邏輯來驗證修改此資源后的最后更新時間。 我添加了一個日期類型為`lastModied`的字段。 ```java package com.howtodoinjava.demo.rest.model; import java.io.Serializable; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "user") public class User implements Serializable { @XmlAttribute(name = "id") private int id; @XmlAttribute(name="uri") private String uri; @XmlElement(name = "firstName") private String firstName; @XmlElement(name = "lastName") private String lastName; @XmlElement(name="last-modified") private Date lastModified; //Setters and Getters ``` ## 步驟 3)在 DAO 層添加訪問和修改資源的方法 我出于示例目的使用了靜態`HashMap`。 在實時應用中,它將是一個數據庫。 例如,我在映射中僅添加了一個用戶。 ```java package com.howtodoinjava.demo.rest.data; import java.util.Date; import java.util.HashMap; import com.howtodoinjava.demo.rest.model.User; public class UserDatabase { public static HashMap<Integer, User> users = new HashMap<Integer, User>(); static { User user = new User(); user.setId(1); user.setFirstName("demo"); user.setLastName("user"); user.setUri("/user-management/users/1"); user.setLastModified(new Date()); users.put(1, user); } public static User getUserById(Integer id) { return users.get(id); } public static void updateUser(Integer id) { User user = users.get(id); user.setLastModified(new Date()); } public static Date getLastModifiedById(Integer id) { return users.get(id).getLastModified(); } } ``` ## 步驟 4)編寫 Restful API 以訪問和修改資源 這是主要步驟。 我已經在上面描述了兩個 API。 GET API 返回附加了 ETag 的用戶資源。 此 ETag 是在用戶資源的最后修改日期計算的。 這將確保每次用戶更新時,都會生成一個新的 ETag。 ```java package com.howtodoinjava.demo.rest.service; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import com.howtodoinjava.demo.rest.data.UserDatabase; @Path("/user-service") public class UserService { @GET @Path("/users/{id}") public Response getUserById(@PathParam("id") int id, @Context Request req) { //Create cache control header CacheControl cc = new CacheControl(); //Set max age to one day cc.setMaxAge(86400); Response.ResponseBuilder rb = null; //Calculate the ETag on last modified date of user resource EntityTag etag = new EntityTag(UserDatabase.getLastModifiedById(id).hashCode()+""); //Verify if it matched with etag available in http request rb = req.evaluatePreconditions(etag); //If ETag matches the rb will be non-null; //Use the rb to return the response without any further processing if (rb != null) { return rb.cacheControl(cc).tag(etag).build(); } //If rb is null then either it is first time request; or resource is modified //Get the updated representation and return with Etag attached to it rb = Response.ok(UserDatabase.getUserById(id)).cacheControl(cc).tag(etag); return rb.build(); } @PUT @Path("/users/{id}") public Response updateUserById(@PathParam("id") int id) { //Update the User resource UserDatabase.updateUser(id); return Response.status(200).build(); } } ``` 警告:HTTP 標頭中使用的日期的粒度不如數據源中使用的某些日期那么精確。 例如,數據庫行中日期的精度可以定義為毫秒。 但是,HTTP 標頭字段中的日期僅精確到秒。 在求值 HTTP 前提條件時,如果將`java.util.Date`對象直接與 HTTP 標頭中的日期進行比較,則精度差異可能會產生意外結果。 為避免此問題,請使用日期對象的哈希碼或使用某些規范化形式。 ## 測試示例代碼 **1)首次請求:GET `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1`** ![User resource request first time](https://img.kancloud.cn/29/f9/29f925535cd0ec77f66e335578cfd43e_943x416.png) 用戶資源的第一次請求 **2)后續請求:GET `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1`** ![User resource subsequent requests](https://img.kancloud.cn/e8/13/e81374cdf1368230db8b5abe40fccefe_709x169.png) 用戶資源的后續請求 **3)修改請求:PUT `http://localhost:8080/RESTEasyEtagDemo/user-s:rvice/users/1`** ![User resource Updated using PUT API](https://img.kancloud.cn/cb/09/cb09ecda6ed2bb7aabb69e323b98d143_955x361.png) 使用 PUT API 更新的用戶資源 **4)更新資源:GET `http://localhost:8080/RESTEasyEtagDemo/user-service/users/1`** ![Update User resource retrieved](https://img.kancloud.cn/2d/73/2d7375e42dd4f8b7d4ad6725ea3df9ae_952x458.png) 檢索更新的用戶資源 要下載以上示例的源代碼,請單擊下面給出的鏈接。 **祝您學習愉快!**
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看