RolePermissionCacheHelper.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package cc.uncarbon.helper;
  2. import cc.uncarbon.framework.core.context.UserContextHolder;
  3. import cn.hutool.core.collection.CollUtil;
  4. import lombok.RequiredArgsConstructor;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.stereotype.Component;
  7. import java.util.*;
  8. /**
  9. * 将角色对应权限,缓存至 Redis
  10. * 参考文章: https://sa-token.cc/doc.html#/fun/jur-cache
  11. *
  12. * @author Uncarbon
  13. */
  14. @Component
  15. @RequiredArgsConstructor
  16. public class RolePermissionCacheHelper {
  17. private final RedisTemplate<String, Collection<String>> stringSetRedisTemplate;
  18. private static final String CACHE_KEY_ROLE_PERMISSIONS = "Authorization:rolePermissions:roleId_%s";
  19. /**
  20. * 从缓存中取得当前用户拥有的所有权限名集合
  21. *
  22. * @return List<String>
  23. */
  24. public List<String> getUserPermissions() {
  25. Set<Long> rolesIds = UserContextHolder.getUserContext().getRolesIds();
  26. if (CollUtil.isEmpty(rolesIds)) {
  27. return Collections.emptyList();
  28. }
  29. // 批量查询缓存
  30. List<String> cacheKeys = rolesIds.stream()
  31. .map(roleId -> String.format(CACHE_KEY_ROLE_PERMISSIONS, roleId))
  32. .toList();
  33. List<Collection<String>> cacheValues = stringSetRedisTemplate.opsForValue().multiGet(cacheKeys);
  34. if (CollUtil.isEmpty(cacheValues)) {
  35. return Collections.emptyList();
  36. }
  37. return cacheValues.stream().flatMap(Collection::stream).toList();
  38. }
  39. /**
  40. * 覆盖更新角色对应权限至 Redis
  41. *
  42. * @param map key=角色ID value=权限集合
  43. */
  44. public void putCache(Map<Long, Set<String>> map) {
  45. Set<Map.Entry<Long, Set<String>>> entries = map.entrySet();
  46. entries.forEach(
  47. entry -> this.putCache(entry.getKey(), entry.getValue())
  48. );
  49. }
  50. /**
  51. * 覆盖更新角色对应权限至 Redis
  52. *
  53. * @param roleId 角色ID
  54. * @param newPermissions 新权限名集合
  55. */
  56. public void putCache(Long roleId, Collection<String> newPermissions) {
  57. String cacheKey = String.format(CACHE_KEY_ROLE_PERMISSIONS, roleId);
  58. stringSetRedisTemplate.opsForValue().set(cacheKey, newPermissions);
  59. }
  60. /**
  61. * 删除角色ID对应的权限缓存
  62. *
  63. * @param roleIds 角色ID集合
  64. */
  65. public void deleteCache(Collection<Long> roleIds) {
  66. if (CollUtil.isNotEmpty(roleIds)) {
  67. // 批量删除缓存
  68. List<String> cacheKeys = roleIds.stream().map(roleId -> String.format(CACHE_KEY_ROLE_PERMISSIONS, roleId)).toList();
  69. stringSetRedisTemplate.delete(cacheKeys);
  70. }
  71. }
  72. }