Guava简单本地缓存使用例子

2018-07-12  本文已影响0人  长坡雪球笑眯眯

简单的本地缓存
整体思路:
把缓存作为全局的静态变量,调用方法时,在方法里从cache获取,没有的话去数据库查,再放入cache

import com.nn.ead.common.dict.DictType;
import com.nn.ead.common.domain.Dict;
import com.nn.ead.common.mapper.DictMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl implements DictService {

    @Resource
    private DictMapper dictMapper;
    //建立本地cache
    private static final Cache<DictType, List<Dict>> cache = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterAccess(1, TimeUnit.DAYS)
            .build();

    @Override
    public String getDesc(DictType dictType, int value) {
        List<Dict> dictList = cache.getIfPresent(dictType);
        if (dictList == null) {
            dictList = dictMapper.selectAll(dictType);
            if (CollectionUtils.isNotEmpty(dictList)) {
                cache.put(dictType, dictList);
            } else {
                return null;
            }
        }
        for (Dict dict : dictList) {
            if (dict.getValue() == value) {
                return dict.getDesc();
            }
        }
        return null;
    }

    @Override
    public Map<Integer, String> getMap(DictType dictType) {
        List<Dict> dictList = cache.getIfPresent(dictType);
        if (dictList == null) {
            dictList = dictMapper.selectAll(dictType);
            if (CollectionUtils.isNotEmpty(dictList)) {
                cache.put(dictType, dictList);
            }
        }
        if (dictList == null) {
            return new HashMap<>();
        }
        return dictList.stream().collect(Collectors.toMap(Dict::getValue, Dict::getDesc));
    }

}
上一篇 下一篇

猜你喜欢

热点阅读