CacheUtils.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.ruoyi.common.utils.redis;
  2. import com.ruoyi.common.utils.spring.SpringUtils;
  3. import lombok.AccessLevel;
  4. import lombok.NoArgsConstructor;
  5. import org.redisson.api.RMap;
  6. import org.springframework.cache.Cache;
  7. import org.springframework.cache.CacheManager;
  8. import java.util.Set;
  9. /**
  10. * 缓存操作工具类 {@link }
  11. *
  12. * @author Michelle.Chung
  13. * @date 2022/8/13
  14. */
  15. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  16. @SuppressWarnings(value = {"unchecked"})
  17. public class CacheUtils {
  18. private static final CacheManager CACHE_MANAGER = SpringUtils.getBean(CacheManager.class);
  19. /**
  20. * 获取缓存组内所有的KEY
  21. *
  22. * @param cacheNames 缓存组名称
  23. */
  24. public static Set<Object> keys(String cacheNames) {
  25. RMap<Object, Object> rmap = (RMap<Object, Object>) CACHE_MANAGER.getCache(cacheNames).getNativeCache();
  26. return rmap.keySet();
  27. }
  28. /**
  29. * 获取缓存值
  30. *
  31. * @param cacheNames 缓存组名称
  32. * @param key 缓存key
  33. */
  34. public static <T> T get(String cacheNames, Object key) {
  35. Cache.ValueWrapper wrapper = CACHE_MANAGER.getCache(cacheNames).get(key);
  36. return wrapper != null ? (T) wrapper.get() : null;
  37. }
  38. /**
  39. * 保存缓存值
  40. *
  41. * @param cacheNames 缓存组名称
  42. * @param key 缓存key
  43. * @param value 缓存值
  44. */
  45. public static void put(String cacheNames, Object key, Object value) {
  46. CACHE_MANAGER.getCache(cacheNames).put(key, value);
  47. }
  48. /**
  49. * 删除缓存值
  50. *
  51. * @param cacheNames 缓存组名称
  52. * @param key 缓存key
  53. */
  54. public static void evict(String cacheNames, Object key) {
  55. CACHE_MANAGER.getCache(cacheNames).evict(key);
  56. }
  57. /**
  58. * 清空缓存值
  59. *
  60. * @param cacheNames 缓存组名称
  61. */
  62. public static void clear(String cacheNames) {
  63. CACHE_MANAGER.getCache(cacheNames).clear();
  64. }
  65. }