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