zoukankan      html  css  js  c++  java
  • Guava Cache 工具类

    maven依赖

    <dependency>
       <groupId>com.google.guava</groupId>
       <artifactId>guava</artifactId>
       <version>23.0</version>
    </dependency>
    import com.google.common.cache.Cache;
    import com.google.common.cache.CacheBuilder;
    import com.google.common.cache.RemovalListener;
    import com.google.common.cache.RemovalNotification;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.util.List;
    import java.util.concurrent.TimeUnit;
    
    
    public class CacheMap {
        private static final Logger log = LoggerFactory.getLogger(CacheMap.class);
    
        /**
         * @desction: 使用google guava缓存处理
         */
        private static Cache<String,Object> cache;
        static {
            cache = CacheBuilder.newBuilder().maximumSize(10000)
                    .expireAfterWrite(24, TimeUnit.HOURS)
                    .initialCapacity(10)
                    .removalListener(new RemovalListener<String, Object>() {
                        @Override
                        public void onRemoval(RemovalNotification<String, Object> rn) {
                            if(log.isInfoEnabled()){
                                log.info("被移除缓存{}:{}",rn.getKey(),rn.getValue());
                            }
                        }
                    }).build();
        }
    
        /**
         * @desction: 获取缓存
         */
        public  static Object get(String key){
            return StringUtils.isNotEmpty(key)?cache.getIfPresent(key):null;
        }
        /**
         * @desction: 放入缓存
         */
        public static void put(String key,Object value){
            if(StringUtils.isNotEmpty(key) && value !=null){
                cache.put(key,value);
            }
        }
        /**
         * @desction: 移除缓存
         */
        public static void remove(String key){
            if(StringUtils.isNotEmpty(key)){
                cache.invalidate(key);
            }
        }
        /**
         * @desction: 批量删除缓存
         */
        public static void remove(List<String> keys){
            if(keys !=null && keys.size() >0){
                cache.invalidateAll(keys);
            }
        }
    } 
  • 相关阅读:
    Spring注解
    [Exception Android 22]
    Android中Word转Html
    [Exception Android 20]
    POI-word转html
    【JS设计模式】装饰者模式
    C语言中的传值调用
    Spring Aop基础总结
    Android开发-状态栏着色原理和API版本号兼容处理
    9.12測试(二)——国际象棋
  • 原文地址:https://www.cnblogs.com/shihaiming/p/11428080.html
Copyright © 2011-2022 走看看