当前位置: 首页 > 教程 > HttpClient >

HttpClient Http缓存示例

精华
小牛编辑
109浏览
2023-03-14

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