Java本地缓存解决方案---使用Google的CacheBuilder

一、背景

当业务实现上需要用到本地缓存,来解决一些数据量相对较小但是频繁访问数据的场景,可以采用Google的CacheBuilder解决方案。

二、代码实现

1. 首先在maven中引入下面的包

<dependency>  
    <groupId>com.google.guava</groupId>  
    <artifactId>guava</artifactId>  
    <version>19.0</version>  
</dependency>

2. 代码测试案例

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.TimeUnit;

public class LocalCacheTest {
    // 测试类
    public static void main(String[] args) throws Exception {
        CacheService us = new CacheService();
        for (int i = 0; i < 6; i++) {
            System.out.println(us.getName("1001"));
            TimeUnit.SECONDS.sleep(1);
        }
    }

    // 实现类
    public static class CacheService {
        private final LoadingCache<String, String> cache;

        public CacheService() {
            /**
             * 创建本地缓存,当本地缓存不命中时,调用load方法,返回结果,再缓存结果, 3秒自动过期
             */
            cache = CacheBuilder.newBuilder().expireAfterWrite(3, TimeUnit.SECONDS)
                    .build(new CacheLoader<String, String>() {
                public String load(String id) throws Exception {
                    System.out.println("load()method invoke, 执行查询数据库, 等其他复杂的逻辑");
                    TimeUnit.MILLISECONDS.sleep(100);
                    return "User:" + id;
                }
            });
        }

        public String getName(String id) throws Exception {
            long start = System.currentTimeMillis();
            String result = cache.get(id);
            System.out.println("查询 "+id +" 耗时:"+ (System.currentTimeMillis()-start) + " ms");
            return result;
        }
    }
}

3. 控制台输出

        从控制台输出,可以看出,当本地缓存不命中时,调用load方法,通过数据库查询结果,返回结果,再缓存结果, 耗时较长。如果命中查询速度非常快,可达0ms,3秒自动过期后,重复上述操作。

load()method invoke, 执行查询数据库, 等其他复杂的逻辑
查询 1001 耗时:124 ms
User:1001
查询 1001 耗时:0 ms
User:1001
查询 1001 耗时:0 ms
User:1001
load()method invoke, 执行查询数据库, 等其他复杂的逻辑
查询 1001 耗时:108 ms
User:1001
查询 1001 耗时:0 ms
User:1001
查询 1001 耗时:0 ms
User:1001

Process finished with exit code 0

4. 附工具类

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

import java.util.concurrent.TimeUnit;

public final class JvmCacheUtil {

    public static final String JVM_CACHE_SPECIFY_GEO = "cache_specify_geo";

    public static final String JVM_CACHE_BUILD_SQL = "cache_build_sql";

    public static final int DEFAULT_CAPACITY = 50;

    public static final long DEFAULT_CACHE_EXP = 12L;

    public static final long DEFAULT_CACHE_ENTRY_EXP = 900L;
    
/**
* 12小时后过期
*/
private static Cache<String, Cache> cacheManager = CacheBuilder.newBuilder() .maximumSize(DEFAULT_CAPACITY) .expireAfterAccess(12L, TimeUnit.HOURS) .expireAfterWrite(12L, TimeUnit.HOURS) .initialCapacity(10) .build(); public static Cache getCache(String cacheName) { return getCache(cacheName, DEFAULT_CAPACITY, DEFAULT_CACHE_ENTRY_EXP, TimeUnit.SECONDS); } public static Cache getCache(String cacheName, long expire, TimeUnit timeUnit) { return getCache(cacheName, DEFAULT_CAPACITY, expire, timeUnit); } public static Cache getCache(String cacheName, int capacity, long expire, TimeUnit timeUnit) { Cache cache = cacheManager.getIfPresent(cacheName); if (null == cache) { cache = CacheBuilder.newBuilder() .maximumSize(DEFAULT_CAPACITY) .expireAfterAccess(expire, timeUnit) .expireAfterWrite(expire, timeUnit) .initialCapacity(capacity) .build(); cacheManager.put(cacheName, cache); } return cache; } public static Object get(String cacheName, String key) { Cache cache = getCache(cacheName); return cache.getIfPresent(key); } public static void put(String cacheName, String key, Object val) { Cache cache = getCache(cacheName); cache.put(key, val); } public static void put(String cacheName, String key, Object val, long expire, TimeUnit timeUnit) { Cache cache = getCache(cacheName, expire, timeUnit); cache.put(key, val); }

 

posted @ 2021-12-13 11:15  屠城校尉杜  阅读(3336)  评论(0编辑  收藏  举报