java专题Java 杂谈

使用google的guavaCache来做二级缓存

2018-06-20  本文已影响2人  H_Man

使用guavaCache做一个缓存,这次主要是使用了定时过期的一个特性,由于存储时间短,所以没有使用redis

@Component
public class BaseGuavaCache {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseGuavaCache.class);

    private static LoadingCache<Integer, UserInfoBean> userInfoCache;
    @Autowired
    private IUserService userService;
    
    @PostConstruct
    public void init() {
    
        userInfoCache = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build(new CacheLoader<Integer, UserInfoBean>() {
            @Override
            public UserInfoBean load(Integer userId) throws Exception {
                UserInfoBean userInfoByCache = userServiceV2.getUserInfoByCache(userId, ConstUtil.RequestType.BACK);
                return userInfoByCache;
            }
        });
        
    }

    
    
    public UserInfoBean getUserInfo(int userId) {
        try {
            return userInfoCache.get(userId);
        } catch (ExecutionException e) {
            LOGGER.error("query userInfo error. userId={}", userId, e);
            return null;
        }
    }

}

上一篇 下一篇

猜你喜欢

热点阅读