RandomObjectRedisCache.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package cn.com.qmth.examcloud.web.cache;
  2. import org.apache.commons.lang3.StringUtils;
  3. import org.assertj.core.util.Arrays;
  4. import cn.com.qmth.examcloud.commons.exception.ExamCloudRuntimeException;
  5. import cn.com.qmth.examcloud.web.redis.RedisClient;
  6. import cn.com.qmth.examcloud.web.support.SpringContextHolder;
  7. /**
  8. * 随机redis缓存
  9. *
  10. * @author WANGWEI
  11. * @date 2019年4月25日
  12. * @Copyright (c) 2018-? http://qmth.com.cn All Rights Reserved.
  13. * @param <T>
  14. */
  15. public abstract class RandomObjectRedisCache<T extends RandomCacheBean> implements ObjectCache<T> {
  16. private RedisClient redisClient;
  17. private RedisClient getRedisClient() {
  18. if (null == redisClient) {
  19. redisClient = SpringContextHolder.getBean(RedisClient.class);
  20. }
  21. return redisClient;
  22. }
  23. protected abstract String getKeyPrefix();
  24. protected abstract int getTimeout();
  25. protected String buildKey(Object... keys) {
  26. String key = getKeyPrefix() + StringUtils.join(Arrays.asList(keys), '_');
  27. return key;
  28. }
  29. private T getFromCache(String key) {
  30. Object object = getRedisClient().get(key, Object.class);
  31. @SuppressWarnings("unchecked")
  32. T t = (T) object;
  33. return t;
  34. }
  35. @Override
  36. public T get(Object... keys) {
  37. String key = buildKey(keys);
  38. T t = getFromCache(key);
  39. if (null == t) {
  40. refresh(keys);
  41. }
  42. t = getFromCache(key);
  43. return t;
  44. }
  45. @Override
  46. public void remove(Object... keys) {
  47. String key = buildKey(keys);
  48. getRedisClient().delete(key);
  49. }
  50. @Override
  51. public void refresh(Object... keys) {
  52. String key = buildKey(keys);
  53. T t = null;
  54. try {
  55. t = loadFromResource(keys);
  56. } catch (Exception e) {
  57. throw new ExamCloudRuntimeException("fail to load data. key=" + key, e);
  58. }
  59. if (null != t) {
  60. getRedisClient().set(key, t, getTimeout());
  61. } else {
  62. getRedisClient().delete(key);
  63. }
  64. }
  65. }