feat(tenant): 实现多租户功能支持

This commit is contained in:
Ray.Hao
2025-12-10 21:14:37 +08:00
parent f16c1e6227
commit 329b3551f7
17 changed files with 1787 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
package com.youlai.boot.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 忽略多租户注解
* <p>
* 标注在方法或类上,表示该方法或类下的所有方法忽略多租户过滤
* 适用于系统管理、租户管理等不需要租户隔离的场景
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreTenant {
}

View File

@@ -0,0 +1,80 @@
package com.youlai.boot.common.tenant;
import lombok.extern.slf4j.Slf4j;
/**
* 租户上下文工具类
* <p>
* 使用 ThreadLocal 存储当前线程的租户ID确保线程安全
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Slf4j
public class TenantContextHolder {
/**
* 租户ID线程本地变量
*/
private static final ThreadLocal<Long> TENANT_ID_HOLDER = new ThreadLocal<>();
/**
* 忽略租户标志(用于某些场景下临时跳过租户过滤)
*/
private static final ThreadLocal<Boolean> IGNORE_TENANT_HOLDER = new ThreadLocal<>();
/**
* 设置当前租户ID
*
* @param tenantId 租户ID
*/
public static void setTenantId(Long tenantId) {
if (tenantId != null) {
TENANT_ID_HOLDER.set(tenantId);
log.debug("设置当前租户ID: {}", tenantId);
}
}
/**
* 获取当前租户ID
*
* @return 租户ID如果未设置则返回 null
*/
public static Long getTenantId() {
return TENANT_ID_HOLDER.get();
}
/**
* 设置忽略租户标志
*
* @param ignore 是否忽略
*/
public static void setIgnoreTenant(boolean ignore) {
IGNORE_TENANT_HOLDER.set(ignore);
log.debug("设置忽略租户标志: {}", ignore);
}
/**
* 是否忽略租户
*
* @return true-忽略false-不忽略
*/
public static boolean isIgnoreTenant() {
Boolean ignore = IGNORE_TENANT_HOLDER.get();
return ignore != null && ignore;
}
/**
* 清除当前线程的租户上下文
* <p>
* 必须在请求结束时调用,避免线程池复用导致的数据泄露
* </p>
*/
public static void clear() {
TENANT_ID_HOLDER.remove();
IGNORE_TENANT_HOLDER.remove();
log.debug("清除租户上下文");
}
}

View File

@@ -0,0 +1,62 @@
package com.youlai.boot.config.property;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 多租户配置属性
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@Component
@ConfigurationProperties(prefix = "youlai.tenant")
public class TenantProperties {
/**
* 是否启用多租户功能
* 默认false不启用
*/
private Boolean enabled = false;
/**
* 租户字段名
* 默认tenant_id
*/
private String column = "tenant_id";
/**
* 默认租户ID用于兼容旧数据tenant_id 为 NULL 时使用)
* 默认1
*/
private Long defaultTenantId = 1L;
/**
* 忽略多租户过滤的表名列表
* 系统表、租户表等不需要租户隔离的表
*/
private List<String> ignoreTables = new ArrayList<>();
/**
* 请求头中的租户ID字段名
* 默认tenant-id
*/
private String headerName = "tenant-id";
/**
* 初始化默认忽略的表
*/
public TenantProperties() {
// 系统表默认忽略多租户
ignoreTables.add("sys_tenant");
ignoreTables.add("sys_dict");
ignoreTables.add("sys_dict_item");
ignoreTables.add("sys_config");
}
}

View File

@@ -0,0 +1,46 @@
package com.youlai.boot.core.aspect;
import com.youlai.boot.common.annotation.IgnoreTenant;
import com.youlai.boot.common.tenant.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 多租户切面
* <p>
* 处理 @IgnoreTenant 注解,临时跳过租户过滤
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Aspect
@Component
@Order(1)
@Slf4j
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class TenantAspect {
/**
* 环绕通知:处理 @IgnoreTenant 注解
*/
@Around("@annotation(ignoreTenant) || @within(ignoreTenant)")
public Object around(ProceedingJoinPoint joinPoint, IgnoreTenant ignoreTenant) throws Throwable {
try {
// 设置忽略租户标志
TenantContextHolder.setIgnoreTenant(true);
log.debug("方法 {} 忽略多租户过滤", joinPoint.getSignature().getName());
// 执行原方法
return joinPoint.proceed();
} finally {
// 恢复租户过滤
TenantContextHolder.setIgnoreTenant(false);
}
}
}

View File

@@ -0,0 +1,72 @@
package com.youlai.boot.core.filter;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.config.property.TenantProperties;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 租户上下文过滤器
* <p>
* 从请求头中获取租户ID设置到线程上下文
* 请求结束时自动清除上下文,避免线程池复用导致的数据泄露
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Slf4j
@Component
@Order(1) // 确保在其他过滤器之前执行
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class TenantContextFilter extends OncePerRequestFilter {
private final TenantProperties tenantProperties;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
// 从请求头获取租户ID
String tenantIdStr = request.getHeader(tenantProperties.getHeaderName());
if (StringUtils.hasText(tenantIdStr)) {
try {
Long tenantId = Long.parseLong(tenantIdStr);
TenantContextHolder.setTenantId(tenantId);
log.debug("从请求头获取租户ID: {}", tenantId);
} catch (NumberFormatException e) {
log.warn("租户ID格式错误: {}", tenantIdStr);
}
} else {
// 如果未提供租户ID使用默认租户ID
Long defaultTenantId = tenantProperties.getDefaultTenantId();
if (defaultTenantId != null) {
TenantContextHolder.setTenantId(defaultTenantId);
log.debug("使用默认租户ID: {}", defaultTenantId);
}
}
// 继续执行过滤器链
filterChain.doFilter(request, response);
} finally {
// 请求结束时清除租户上下文,避免线程池复用导致的数据泄露
TenantContextHolder.clear();
}
}
}

View File

@@ -0,0 +1,90 @@
package com.youlai.boot.plugin.mybatis;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.config.property.TenantProperties;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* MyBatis-Plus 多租户处理器
* <p>
* 实现 TenantLineHandler 接口,自动为 SQL 添加租户过滤条件
* 仅在启用多租户时注册(通过 @ConditionalOnProperty 控制)
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class TenantLineHandler implements com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler {
private final TenantProperties tenantProperties;
/**
* 获取租户ID表达式
* <p>
* 从 TenantContextHolder 获取当前租户ID
* 如果未设置或忽略租户,返回 NULL不添加租户条件
* </p>
*
* @return 租户ID表达式
*/
@Override
public Expression getTenantId() {
// 如果设置了忽略租户标志,返回 NULL不添加租户条件
if (TenantContextHolder.isIgnoreTenant()) {
return new NullValue();
}
// 获取当前租户ID
Long tenantId = TenantContextHolder.getTenantId();
// 如果未设置租户ID使用默认租户ID
if (tenantId == null) {
tenantId = tenantProperties.getDefaultTenantId();
}
return new LongValue(tenantId);
}
/**
* 获取租户字段名
*
* @return 租户字段名
*/
@Override
public String getTenantIdColumn() {
return tenantProperties.getColumn();
}
/**
* 判断表是否忽略多租户过滤
* <p>
* 系统表、租户表等不需要租户隔离的表应返回 true
* </p>
*
* @param tableName 表名
* @return true-忽略false-不忽略
*/
@Override
public boolean ignoreTable(String tableName) {
List<String> ignoreTables = tenantProperties.getIgnoreTables();
if (ignoreTables == null || ignoreTables.isEmpty()) {
return false;
}
// 忽略表名匹配(不区分大小写)
return ignoreTables.stream()
.anyMatch(ignoreTable -> ignoreTable.equalsIgnoreCase(tableName));
}
}

View File

@@ -0,0 +1,110 @@
package com.youlai.boot.system.controller;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.core.web.Result;
import com.youlai.boot.security.util.SecurityUtils;
import com.youlai.boot.system.model.vo.TenantVO;
import com.youlai.boot.system.service.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 租户管理控制器
* <p>
* 提供租户切换、查询等功能
* </p>
*
* @author Ray.Hao
* @since 3.0.0
*/
@Tag(name = "租户管理接口")
@RestController
@RequestMapping("/api/v1/tenant")
@RequiredArgsConstructor
@Slf4j
@ConditionalOnProperty(prefix = "youlai.tenant", name = "enabled", havingValue = "true", matchIfMissing = false)
public class TenantController {
private final TenantService tenantService;
/**
* 获取当前用户的租户列表
* <p>
* 根据当前登录用户查询其所属的所有租户
* </p>
*
* @return 租户列表
*/
@Operation(summary = "获取当前用户的租户列表")
@GetMapping("/list")
public Result<List<TenantVO>> getTenantList() {
Long userId = SecurityUtils.getUserId();
List<TenantVO> tenantList = tenantService.getTenantListByUserId(userId);
log.info("获取用户 {} 的租户列表,共 {} 个租户", userId, tenantList.size());
return Result.success(tenantList);
}
/**
* 获取当前租户信息
*
* @return 当前租户信息
*/
@Operation(summary = "获取当前租户信息")
@GetMapping("/current")
public Result<TenantVO> getCurrentTenant() {
Long tenantId = TenantContextHolder.getTenantId();
if (tenantId == null) {
return Result.success(null);
}
TenantVO tenant = tenantService.getTenantById(tenantId);
return Result.success(tenant);
}
/**
* 切换租户
* <p>
* 切换当前用户的租户上下文,需要验证用户是否有权限访问该租户
* </p>
*
* @param tenantId 目标租户ID
* @return 切换结果
*/
@Operation(summary = "切换租户")
@PostMapping("/switch/{tenantId}")
public Result<TenantVO> switchTenant(
@Parameter(description = "租户ID") @PathVariable Long tenantId
) {
Long userId = SecurityUtils.getUserId();
log.info("用户 {} 请求切换租户到 {}", userId, tenantId);
// 验证用户是否有权限访问该租户
boolean hasPermission = tenantService.hasTenantPermission(userId, tenantId);
if (!hasPermission) {
log.warn("用户 {} 无权限访问租户 {}", userId, tenantId);
return Result.failed("无权限访问该租户");
}
// 验证租户是否存在且正常
TenantVO tenant = tenantService.getTenantById(tenantId);
if (tenant == null) {
return Result.failed("租户不存在");
}
if (tenant.getStatus() == null || tenant.getStatus() != 1) {
return Result.failed("租户已禁用");
}
// 设置新的租户上下文
TenantContextHolder.setTenantId(tenantId);
log.info("用户 {} 成功切换租户到 {}", userId, tenantId);
return Result.success(tenant);
}
}

View File

@@ -0,0 +1,16 @@
package com.youlai.boot.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youlai.boot.system.model.entity.Tenant;
import org.apache.ibatis.annotations.Mapper;
/**
* 租户 Mapper
*
* @author Ray.Hao
* @since 3.0.0
*/
@Mapper
public interface TenantMapper extends BaseMapper<Tenant> {
}

View File

@@ -0,0 +1,16 @@
package com.youlai.boot.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youlai.boot.system.model.entity.UserTenant;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户租户关联 Mapper
*
* @author Ray.Hao
* @since 3.0.0
*/
@Mapper
public interface UserTenantMapper extends BaseMapper<UserTenant> {
}

View File

@@ -0,0 +1,71 @@
package com.youlai.boot.system.model.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.youlai.boot.common.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 租户实体
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_tenant")
public class Tenant extends BaseEntity {
/**
* 租户名称
*/
private String name;
/**
* 租户编码(唯一)
*/
private String code;
/**
* 联系人姓名
*/
private String contactName;
/**
* 联系人电话
*/
private String contactPhone;
/**
* 联系人邮箱
*/
private String contactEmail;
/**
* 租户域名(用于域名识别)
*/
private String domain;
/**
* 租户Logo
*/
private String logo;
/**
* 状态(1-正常 0-禁用)
*/
private Integer status;
/**
* 备注
*/
private String remark;
/**
* 过期时间NULL表示永不过期
*/
private LocalDateTime expireTime;
}

View File

@@ -0,0 +1,34 @@
package com.youlai.boot.system.model.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.youlai.boot.common.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 用户租户关联实体
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_user_tenant")
public class UserTenant extends BaseEntity {
/**
* 用户ID
*/
private Long userId;
/**
* 租户ID
*/
private Long tenantId;
/**
* 是否默认租户(1-是 0-否)
*/
private Integer isDefault;
}

View File

@@ -0,0 +1,48 @@
package com.youlai.boot.system.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
/**
* 租户VO
*
* @author Ray.Hao
* @since 3.0.0
*/
@Data
@Schema(description = "租户信息")
public class TenantVO implements Serializable {
@Schema(description = "租户ID")
private Long id;
@Schema(description = "租户名称")
private String name;
@Schema(description = "租户编码")
private String code;
@Schema(description = "租户状态(1-正常 0-禁用)")
private Integer status;
@Schema(description = "联系人姓名")
private String contactName;
@Schema(description = "联系人电话")
private String contactPhone;
@Schema(description = "联系人邮箱")
private String contactEmail;
@Schema(description = "租户域名")
private String domain;
@Schema(description = "租户Logo")
private String logo;
@Schema(description = "是否默认租户")
private Boolean isDefault;
}

View File

@@ -0,0 +1,50 @@
package com.youlai.boot.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.youlai.boot.system.model.entity.Tenant;
import com.youlai.boot.system.model.vo.TenantVO;
import java.util.List;
/**
* 租户服务接口
*
* @author Ray.Hao
* @since 3.0.0
*/
public interface TenantService extends IService<Tenant> {
/**
* 根据用户ID查询用户所属的租户列表
*
* @param userId 用户ID
* @return 租户列表
*/
List<TenantVO> getTenantListByUserId(Long userId);
/**
* 根据租户ID查询租户信息
*
* @param tenantId 租户ID
* @return 租户信息
*/
TenantVO getTenantById(Long tenantId);
/**
* 根据域名查询租户ID
*
* @param domain 域名
* @return 租户ID
*/
Long getTenantIdByDomain(String domain);
/**
* 验证用户是否有权限访问指定租户
*
* @param userId 用户ID
* @param tenantId 租户ID
* @return true-有权限false-无权限
*/
boolean hasTenantPermission(Long userId, Long tenantId);
}

View File

@@ -0,0 +1,125 @@
package com.youlai.boot.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.common.tenant.TenantContextHolder;
import com.youlai.boot.system.mapper.TenantMapper;
import com.youlai.boot.system.mapper.UserTenantMapper;
import com.youlai.boot.system.model.entity.Tenant;
import com.youlai.boot.system.model.entity.UserTenant;
import com.youlai.boot.system.model.vo.TenantVO;
import com.youlai.boot.system.service.TenantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* 租户服务实现类
*
* @author Ray.Hao
* @since 3.0.0
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
private final UserTenantMapper userTenantMapper;
@Override
public List<TenantVO> getTenantListByUserId(Long userId) {
// 临时忽略租户过滤,查询所有租户
TenantContextHolder.setIgnoreTenant(true);
try {
// 查询用户关联的租户ID列表
List<UserTenant> userTenants = userTenantMapper.selectList(
new LambdaQueryWrapper<UserTenant>()
.eq(UserTenant::getUserId, userId)
);
if (userTenants.isEmpty()) {
return List.of();
}
// 提取租户ID列表
List<Long> tenantIds = userTenants.stream()
.map(UserTenant::getTenantId)
.collect(Collectors.toList());
// 查询租户信息
List<Tenant> tenants = this.list(
new LambdaQueryWrapper<Tenant>()
.in(Tenant::getId, tenantIds)
.eq(Tenant::getStatus, 1) // 只查询正常状态的租户
.orderByDesc(Tenant::getId)
);
// 转换为VO并标记默认租户
return tenants.stream().map(tenant -> {
TenantVO vo = new TenantVO();
BeanUtils.copyProperties(tenant, vo);
// 查找是否为默认租户
userTenants.stream()
.filter(ut -> ut.getTenantId().equals(tenant.getId()) && ut.getIsDefault() == 1)
.findFirst()
.ifPresent(ut -> vo.setIsDefault(true));
return vo;
}).collect(Collectors.toList());
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
@Override
public TenantVO getTenantById(Long tenantId) {
TenantContextHolder.setIgnoreTenant(true);
try {
Tenant tenant = this.getById(tenantId);
if (tenant == null) {
return null;
}
TenantVO vo = new TenantVO();
BeanUtils.copyProperties(tenant, vo);
return vo;
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
@Override
public Long getTenantIdByDomain(String domain) {
TenantContextHolder.setIgnoreTenant(true);
try {
Tenant tenant = this.getOne(
new LambdaQueryWrapper<Tenant>()
.eq(Tenant::getDomain, domain)
.eq(Tenant::getStatus, 1)
.last("LIMIT 1")
);
return tenant != null ? tenant.getId() : null;
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
@Override
public boolean hasTenantPermission(Long userId, Long tenantId) {
TenantContextHolder.setIgnoreTenant(true);
try {
UserTenant userTenant = userTenantMapper.selectOne(
new LambdaQueryWrapper<UserTenant>()
.eq(UserTenant::getUserId, userId)
.eq(UserTenant::getTenantId, tenantId)
.last("LIMIT 1")
);
return userTenant != null;
} finally {
TenantContextHolder.setIgnoreTenant(false);
}
}
}