package cn.com.qmth.examcloud.web.cache; import org.apache.commons.lang3.StringUtils; import org.assertj.core.util.Arrays; import cn.com.qmth.examcloud.commons.exception.ExamCloudRuntimeException; import cn.com.qmth.examcloud.web.redis.RedisClient; import cn.com.qmth.examcloud.web.support.SpringContextHolder; /** * 随机redis缓存 * * @author WANGWEI * @date 2019年4月25日 * @Copyright (c) 2018-? http://qmth.com.cn All Rights Reserved. * @param */ public abstract class RandomObjectRedisCache implements ObjectCache { private RedisClient redisClient; private RedisClient getRedisClient() { if (null == redisClient) { redisClient = SpringContextHolder.getBean(RedisClient.class); } return redisClient; } protected abstract String getKeyPrefix(); protected abstract int getTimeout(); protected String buildKey(Object... keys) { String key = getKeyPrefix() + StringUtils.join(Arrays.asList(keys), '_'); return key; } private T getFromCache(String key) { Object object = getRedisClient().get(key, Object.class); @SuppressWarnings("unchecked") T t = (T) object; return t; } @Override public T get(Object... keys) { String key = buildKey(keys); T t = getFromCache(key); if (null == t) { refresh(keys); } t = getFromCache(key); return t; } @Override public void remove(Object... keys) { String key = buildKey(keys); getRedisClient().delete(key); } @Override public void refresh(Object... keys) { String key = buildKey(keys); T t = null; try { t = loadFromResource(keys); } catch (Exception e) { throw new ExamCloudRuntimeException("fail to load data. key=" + key, e); } if (null != t) { getRedisClient().set(key, t, getTimeout()); } else { getRedisClient().delete(key); } } }