HttpClient Http快取範例


HttpClient Cache提供了一個與HTTP / 1.1相容的快取層,可以與HttpClient一起使用 - Java相當於瀏覽器快取。 以下範例使用HttpClient快取庫的CacheConfig

Maven依賴關係

我們使用maven來管理依賴關係,並使用Apache HttpClient 4.5版本。 將以下依賴項新增到您的專案中。

pom.xml 檔案的內容如下 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

HttpClient快取範例

這是如何設定基本快取HttpClient的簡單範例。 按照組態,它將儲存最多3000個快取物件,其中每個物件的最大主體大小可能為10240位元組。 我們組態CacheConfig並使用這個組態來建立HttpClient。 迴圈執行一次簡單的HTTP GET請求3次,並期望最後兩個請求將被快取。

檔案:HttpClientCachingExample.java -

package com.yiibai.httpdemo;

import org.apache.http.client.cache.CacheResponseStatus;
import org.apache.http.client.cache.HttpCacheContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.CachingHttpClients;

import java.io.IOException;

/**
 * This example demonstrates how to use caching {@link CacheConfig}.
 */
public class HttpClientCachingExample {

    public static void main(String... args) throws IOException {

        CacheConfig cacheConfig = CacheConfig.custom()
                .setMaxCacheEntries(3000)
                .setMaxObjectSize(10240) // 10MB
                .build();

        CloseableHttpClient cachingClient = CachingHttpClients.custom()
                .setCacheConfig(cacheConfig)
                .build();

        for (int i = 0; i < 3; i++){
            HttpCacheContext context = HttpCacheContext.create();
            HttpGet httpget = new HttpGet("http://httpbin.org/cache");
            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = cachingClient.execute(httpget, context);
            try {
                System.out.println("----------------------------------------");
                CacheResponseStatus responseStatus = context.getCacheResponseStatus();
                switch (responseStatus) {
                    case CACHE_HIT:
                        System.out.println("A response was generated from the cache with " +
                                "no requests sent upstream");
                        break;
                    case CACHE_MODULE_RESPONSE:
                        System.out.println("The response was generated directly by the " +
                                "caching module");
                        break;
                    case CACHE_MISS:
                        System.out.println("The response came from an upstream server");
                        break;
                    case VALIDATED:
                        System.out.println("The response was generated from the cache " +
                                "after validating the entry with the origin server");
                        break;
                }
            } finally {
                response.close();
            }
        }
    }

}

執行上面範例程式碼,得到以下結果 -

Executing request GET http://httpbin.org/cache HTTP/1.1
----------------------------------------
The response came from an upstream server
Executing request GET http://httpbin.org/cache HTTP/1.1
----------------------------------------
The response was generated from the cache after validating the entry with the origin server
Executing request GET http://httpbin.org/cache HTTP/1.1
----------------------------------------
The response was generated from the cache after validating the entry with the origin server

以下是糾正/補充內容:

4.5.2版本的這個包,根本就要沒有這些類了,如CacheConfigCachingHttpClients等。  提交時間:2019-09-11