12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- 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 <T>
- */
- public abstract class RandomObjectRedisCache<T extends RandomCacheBean> implements ObjectCache<T> {
- 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);
- }
- }
- }
|