Guava简单本地缓存使用例子

简单的本地缓存
整体思路:
把缓存作为全局的静态变量,调用方法时,在方法里从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));
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容