Use of Google Guava Cache

1 Introduction

Google Guava Cache is a cache framework in the Google Guava library, which is used to cache calculation results, data or resources, and improve program access efficiency and response speed. Guava Cache has the following characteristics:

①Configurability: Guava Cache supports the configuration of various cache parameters, such as cache size, expiration time, access policy, etc., which can be flexibly configured according to application scenarios.

②Recycling strategy based on reference counting: Guava Cache uses a recycling strategy based on reference counting. When the reference count of the cached object is 0, it is automatically recycled to avoid memory leaks.

③Multi-thread safety: Guava Cache is thread-safe and supports concurrent reading and writing, ensuring that multiple threads can safely access and operate cached data.

④Easy to use: Guava Cache provides an easy-to-use API, which can easily read, add, delete and update cached data, reducing the difficulty and complexity of development.

2. Dependency introduction

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>32.1.2-jre</version>
</dependency>

3. Cache

3.1 LoadingCache

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

public class LoadingCacheTest {

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

    private static LoadingCache<String, String> loadingCache = CacheBuilder
            .newBuilder()
            .maximumSize(2) // 缓存的个数
            .removalListener(listener) // 移除缓存时的监听事件
            .build(new CacheLoader<String, String>() {
                @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"));
    }

}

operation result:

 

 The maximum number of caches set here is 2. When the third one is cached, the listening event of removing the cache will be triggered, so the result prints the remove key.

You can set the cache expiration time expireAfterWrite:

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

public class LoadingCacheTest {

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

    private static LoadingCache<String, String> loadingCache = CacheBuilder
            .newBuilder()
            .maximumSize(5)
            .removalListener(listener)
            .expireAfterWrite(2,TimeUnit.SECONDS)
            .build(new CacheLoader<String, String>() {
                @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"));
    }

}

operation result:

 

 

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<String, String> 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"));
    }
}

operation result:

 Cachey can also set monitoring, expiration time, etc.:

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<String,String> listener = notification -> System.err.println("remove key:" + notification.getKey());


    private static Cache<String, String> 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"));
    }
}

operation result:

Related documentation: https://github.com/google/guava/wiki/CachesExplained

Guess you like

Origin blog.csdn.net/qq_41061437/article/details/132424220