Guava Cache local cache (LoadingCache)

In the development application, which can not use the cache, distributed cache usually used redis, Memcache and other commonly used, many of the local cache that is also used as ehcache 

Today google guava introduced under the framework provided by the plug LoadingCache local cache, LoadingCache and ConcurrentMap are similar thread-safe, but more than ConcurrentMap some other features, such as expired strategies

advantage

1, thread-safe cache, and ConcurrentMap similar, but the former added more elements expiration policy, removing elements which can only be displayed.
2, provides three basic cache recovery methods: based on the reference capacity recovery recycling, recovery and a timing-based. Timing recovery in two ways: according to the write time, the first write recovery earliest; in accordance with the access time, the first recovered recently accessed.
3, load monitoring cache / hit situation.
4 integrates multiple operations, calls get way, you can cache miss when acquiring data source (DB, redis) from elsewhere, and loaded into the cache

 

Readily write a simple class (room for improvement)

package com.shentb.hmb.cache;

import com.google.common.cache.*;
import com.shentb.hmb.service.impl.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public final class LoadingLocalCache {

    private static LoginService loginService;

    private static Logger logger = LoggerFactory.getLogger(LoadingLocalCache.class);

    private static LoadingCache<String, Object> loadingCache;

    private static LoadingLocalCache loadingLocalCache;

    private static int DEFAULT_CONCURRENCY_LEVEL= 4;

    private static int DEFAULT_EXPIRE= 1800;

    private static int DEFAULT_INITIAL_CAPACITY= 16;

    private static int DEFAULT_MAXIMUM_SIZE= 100;

    private static TimeUnit DEFAULT_TIME_UNIT= TimeUnit.SECONDS;

    @Autowired
    public void setLoginService(LoginService loginService) {
        LoadingLocalCache.loginService = loginService;
    }

    static {
        init();
    }

    private LoadingLocalCache(){}

    protected static void init() {
        loadingCache= CacheBuilder
                .newBuilder()
                //并发级别(同时写入缓存的线程数)
                .concurrencyLevel(DEFAULT_CONCURRENCY_LEVEL)
                //过期时间
                .expireAfterWrite(DEFAULT_EXPIRE,DEFAULT_TIME_UNIT)
                //初始容量
                .initialCapacity(DEFAULT_INITIAL_CAPACITY)
                //最大容量,超过之后默认按照LRU算法最近使用最少移除缓存项    
                .maximumSize(DEFAULT_MAXIMUM_SIZE)
                //设置统计缓存的命中率
                .recordStats()
                .removalListener(new RemovalListener<Object, Object>() {
                    @Override
                    public void onRemoval(RemovalNotification<Object, Object> notification) {
                        logger.info(notification.getKey() + " was removed, cause is " + notification.getCause());
                    }
                })
                //build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
                .build(
                        new CacheLoader<String, Object>() {
                            @Override
                            public Object load(String key) throws Exception {
                                return loginService.selectByPhoneNo(key);
                            }
                        }
                );
    }

    public static Object put(String key, Object value){
        loadingCache.put(key, value);
        return value;
    }

    public static Object get(String key) throws Exception {
        return loadingCache.get(key);
    }

    public static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw new NullPointerException();
        }
        return reference;
    }


//        System.out.println(sellerContactVOCache.stats().toString());
}

Common methods:

GET (K) : This method either returns the cached value, CacheLoader loading a new value to the cache atomically (the time when the cache is said above, there is no value to perform Load method) or use

PUT (Key, value) : This method can be shown directly insert a value into the cache, which will directly overwrite the value before the mapping has been off key.

Cache recovery:

CacheBuilder.maximumSize (Long) : This method specified number of cache entries does not exceed a fixed value (in fact, you can be understood as a Map of the maximum capacity), try the cache entry is not recovered recently used or rarely used on an overall

Timing recovery (Timed Eviction):

expireAfterAccess (Long, TimeUnit) : cache entry is not read within a given time / write access, then recovered. Note that this recovery order and the same cache size based recovery.

expireAfterWrite (Long, TimeUnit) : cache entry within a given time is not write access (to create or overwrite), then recovered. If that cache data is always unavailable become stale after a fixed time, this recovery is desirable manner.

Explicit clear:

At any time, you can explicitly clear the cache entry, rather than waiting until it is recycled:

Individual clear: Cache.invalidate (Key)   batch clear: Cache.invalidateAll (Keys)   clear all cache entries: Cache.invalidateAll ()

Remove listeners

By CacheBuilder.removalListener (RemovalListener) , you can declare a listener to do some additional operations when the cache entry is removed. When a cache entry is removed, RemovalListener obtains removal notification [ RemovalNotification ], which comprises removing the reasons [ RemovalCause ], keys and values

Published 288 original articles · won praise 88 · views 430 000 +

Guess you like

Origin blog.csdn.net/ypp91zr/article/details/90712195
Recommended