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); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM