RolePermissionCacheHelper.java 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package cc.uncarbon.helper;
  2. import cc.uncarbon.framework.core.context.UserContextHolder;
  3. import cn.hutool.core.collection.CollUtil;
  4. import java.util.*;
  5. import lombok.RequiredArgsConstructor;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.stereotype.Component;
  8. /**
  9. * 将角色对应权限,缓存至 Redis
  10. * 参考文章: https://sa-token.dev33.cn/doc/index.html#/fun/jur-cache
  11. *
  12. * @author Uncarbon
  13. */
  14. @Component
  15. @RequiredArgsConstructor
  16. public class RolePermissionCacheHelper {
  17. private final RedisTemplate<String, Set<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. // aka * 64
  27. List<String> ret = new ArrayList<>(rolesIds.size() << 6);
  28. rolesIds.forEach(
  29. roleId -> {
  30. String cacheKey = String.format(CACHE_KEY_ROLE_PERMISSIONS, roleId);
  31. ret.addAll(CollUtil.emptyIfNull(stringSetRedisTemplate.opsForValue().get(cacheKey)));
  32. }
  33. );
  34. return ret;
  35. }
  36. /**
  37. * 覆盖更新角色对应权限至 Redis
  38. *
  39. * @param map key=角色ID value=权限集合
  40. */
  41. public void putCache(Map<Long, Set<String>> map) {
  42. Set<Map.Entry<Long, Set<String>>> entries = map.entrySet();
  43. entries.forEach(
  44. entry -> this.putCache(entry.getKey(), entry.getValue())
  45. );
  46. }
  47. /**
  48. * 覆盖更新角色对应权限至 Redis
  49. *
  50. * @param roleId 角色ID
  51. * @param newPermissions 新权限名集合
  52. */
  53. public void putCache(Long roleId, Set<String> newPermissions) {
  54. String cacheKey = String.format(CACHE_KEY_ROLE_PERMISSIONS, roleId);
  55. stringSetRedisTemplate.opsForValue().set(cacheKey, newPermissions);
  56. }
  57. /**
  58. * 删除角色ID对应的权限缓存
  59. *
  60. * @param roleIds 角色ID集合
  61. */
  62. public void deleteCache(Collection<Long> roleIds) {
  63. roleIds.forEach(
  64. roleId -> {
  65. String cacheKey = String.format(CACHE_KEY_ROLE_PERMISSIONS, roleId);
  66. stringSetRedisTemplate.delete(cacheKey);
  67. }
  68. );
  69. }
  70. }