feat: 权限缓存加载适配

This commit is contained in:
Ray.Hao
2025-12-12 22:26:43 +08:00
parent 0a594e2ce1
commit 3f05f77351
15 changed files with 210 additions and 91 deletions

View File

@@ -3,6 +3,8 @@ package com.youlai.boot.security.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.config.property.TenantProperties;
import com.youlai.boot.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -24,6 +26,7 @@ import java.util.*;
public class PermissionService {
private final RedisTemplate<String, Object> redisTemplate;
private final TenantProperties tenantProperties;
/**
* 判断当前登录用户是否拥有操作权限
@@ -67,21 +70,36 @@ public class PermissionService {
/**
* 从缓存中获取角色权限列表
* 构建租户权限缓存key
*
* @param tenantId 租户ID
* @return 缓存key
*/
private String buildRolePermsCacheKey(Long tenantId) {
if (!tenantProperties.getEnabled() || tenantId == null) {
return RedisConstants.System.ROLE_PERMS;
}
return RedisConstants.System.ROLE_PERMS + ":" + tenantId;
}
/**
* 从缓存中获取角色权限列表(兼容单租户和多租户)
*
* @param roleCodes 角色编码集合
* @return 角色权限列表
*/
public Set<String> getRolePermsFormCache(Set<String> roleCodes) {
// 检查输入是否为空
if (CollectionUtil.isEmpty(roleCodes)) {
return Collections.emptySet();
}
// 获取当前租户ID并构建缓存Key
Long tenantId = TenantContextHolder.getTenantId();
String cacheKey = buildRolePermsCacheKey(tenantId);
Set<String> perms = new HashSet<>();
// 从缓存中一次性获取所有角色的权限
Collection<Object> roleCodesAsObjects = new ArrayList<>(roleCodes);
List<Object> rolePermsList = redisTemplate.opsForHash().multiGet(RedisConstants.System.ROLE_PERMS, roleCodesAsObjects);
List<Object> rolePermsList = redisTemplate.opsForHash().multiGet(cacheKey, roleCodesAsObjects);
for (Object rolePermsObj : rolePermsList) {
if (rolePermsObj instanceof Set) {