RedisCache.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package com.fjhx.config.redis;
  2. import cn.hutool.extra.spring.SpringUtil;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.data.redis.core.ValueOperations;
  5. import java.util.Collection;
  6. import java.util.concurrent.TimeUnit;
  7. /**
  8. * redis缓存 工具类
  9. **/
  10. @SuppressWarnings(value = {"unchecked", "rawtypes"})
  11. public class RedisCache {
  12. private static final RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate");
  13. /**
  14. * 设置缓存(默认缓存30分钟)
  15. *
  16. * @param key 缓存的键值
  17. * @param value 缓存的值
  18. */
  19. public static void set(String key, Object value) {
  20. redisTemplate.opsForValue().set(key, value);
  21. }
  22. /**
  23. * 设置缓存,并指定过期时间(分钟)
  24. *
  25. * @param key 缓存的键值
  26. * @param value 缓存的值
  27. * @param timeout 时间
  28. */
  29. public static void set(String key, Object value, Integer timeout) {
  30. set(key, value, timeout, TimeUnit.MINUTES);
  31. }
  32. /**
  33. * 设置缓存
  34. *
  35. * @param key 缓存的键值
  36. * @param value 缓存的值
  37. * @param timeout 时间
  38. * @param timeUnit 时间颗粒度
  39. */
  40. public static void set(String key, Object value, Integer timeout, TimeUnit timeUnit) {
  41. redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
  42. }
  43. /**
  44. * 获取缓存
  45. *
  46. * @param key 缓存键值
  47. * @param <T> 放回对象类型
  48. * @return 缓存键值对应的数据
  49. */
  50. public static <T> T get(String key) {
  51. ValueOperations<String, T> operation = redisTemplate.opsForValue();
  52. return operation.get(key);
  53. }
  54. /**
  55. * 删除缓存
  56. *
  57. * @param key 缓存key
  58. */
  59. public static void delete(String key) {
  60. redisTemplate.delete(key);
  61. }
  62. /**
  63. * 获得缓存的基本对象列表
  64. *
  65. * @param pattern 字符串前缀
  66. * @return 对象列表
  67. */
  68. public static Collection<String> keys(final String pattern) {
  69. return redisTemplate.keys(pattern);
  70. }
  71. }