Google Guava Cache的使用

1、前言

Google Guava Cache是Google Guava库中的一个缓存框架,用于缓存计算结果、数据或资源,提高程序访问效率和响应速度。Guava Cache具有以下特点:

①可配置性:Guava Cache支持多种缓存参数的配置,例如缓存大小、过期时间、访问策略等,可以根据应用场景进行灵活配置。

②基于引用计数的回收策略:Guava Cache使用基于引用计数的回收策略,当缓存对象的引用计数为0时自动回收,避免了内存泄漏。

③多线程安全:Guava Cache是线程安全的,支持并发读写,保证多个线程能安全地访问和操作缓存数据。

④易于使用:Guava Cache提供简单易用的API,可以方便地进行缓存数据的读取、添加、删除和更新操作,降低了开发的难度和复杂度。

2、依赖引入



    com.google.guava
    guava
    32.1.2-jre

3、缓存

3.1 LoadingCache

import com.google.common.cache.*;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class LoadingCacheTest {

    private static final RemovalListener listener = notification -> System.err.println("remove key:" + notification.getKey());

    private static LoadingCache loadingCache = CacheBuilder
            .newBuilder()
            .maximumSize(2) // 缓存的个数
            .removalListener(listener) // 移除缓存时的监听事件
            .build(new CacheLoader() {
                @Override
                public String load(String key) {  
                    return key.toUpperCase(Locale.ROOT);
                }
            });
    
    public static void main(String[] args) throws Exception {
        System.out.println("a的缓存:" + loadingCache.get("a"));
        System.out.println("b的缓存:" + loadingCache.get("b"));
        loadingCache.put("c", "C");
        System.out.println("c的缓存:" + loadingCache.get("c"));
    }

}

运行结果:

Google Guava Cache的使用_第1张图片 

 这里设置的最大缓存个数是2,当缓存第三个的时候,就会出发移除缓存的监听事件,因此结果打印了remove key。

可以设置缓存过期时间expireAfterWrite:

import com.google.common.cache.*;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class LoadingCacheTest {

    private static final RemovalListener listener = notification -> System.err.println("remove key:" + notification.getKey());

    private static LoadingCache loadingCache = CacheBuilder
            .newBuilder()
            .maximumSize(5)
            .removalListener(listener)
            .expireAfterWrite(2,TimeUnit.SECONDS)
            .build(new CacheLoader() {
                @Override
                public String load(String key) {
                    return key.toUpperCase(Locale.ROOT);
                }
            });

    public static void main(String[] args) throws Exception {
        System.out.println("a的缓存:" + loadingCache.get("a"));
        System.out.println("b的缓存:" + loadingCache.get("b"));
        Thread.sleep(3000);
        loadingCache.put("c", "C");
        System.out.println("c的缓存:" + loadingCache.get("c"));
    }

}

运行结果:

Google Guava Cache的使用_第2张图片 

 

3.2 Cache

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.ExecutionException;

public class CacheTest {

    private static Cache cache = CacheBuilder.newBuilder().
            maximumSize(10).build();


    public static void main(String[] args) throws ExecutionException {
        cache.put("a", "A");
        System.out.println("cache key a value:" + cache.getIfPresent("a"));
        // 删除值
        cache.invalidate("a");
        System.out.println("invalidate后cache.getIfPresent(a):" + cache.getIfPresent("a"));
        // 添加值
        cache.put("b", "B");
        System.out.println("put后cache.getIfPresent(b):" + cache.getIfPresent("b"));
    }
}

运行结果:

Google Guava Cache的使用_第3张图片

 Cachey也可以设置监听、过期时间等:

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CacheTest {
    private static final RemovalListener listener = notification -> System.err.println("remove key:" + notification.getKey());


    private static Cache cache = CacheBuilder.newBuilder()
            .maximumSize(10)
            .expireAfterWrite(2, TimeUnit.SECONDS)
            .removalListener(listener)
            .build();


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        cache.put("a", "A");
        System.out.println("cache key a value:" + cache.getIfPresent("a"));
        Thread.sleep(3000);
        // 添加值
        cache.put("b", "B");
        System.out.println("put后cache.getIfPresent(b):" + cache.getIfPresent("b"));
    }
}

运行结果:

Google Guava Cache的使用_第4张图片

相关文档:https://github.com/google/guava/wiki/CachesExplained

你可能感兴趣的:(Java学习,框架及三方组件,java)