多租户代码框架

This commit is contained in:
zhonghua1
2025-12-16 23:34:07 +08:00
parent 5453026309
commit 406f7d692b
36 changed files with 956 additions and 39 deletions

View File

@@ -34,10 +34,10 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@MapperScan("com.rj.mapper")
@SpringBootApplication
@EnableScheduling
public class AISmartCard20250803Application {
public class AISmartCard20251230Application {
public static void main(String[] args) {
SpringApplication.run(AISmartCard20250803Application.class, args);
SpringApplication.run(AISmartCard20251230Application.class, args);
}
}

View File

@@ -2,35 +2,82 @@ package com.rj.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.rj.tenant.TenantContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.HashSet;
import java.util.Set;
/**
* MyBatis Plus 配置类
*
* @author 李中华
* @since 2025-08-08
*
* <p>包含:</p>
* <ul>
* <li>多租户拦截器根据当前线程中的租户ID自动为SQL拼接 tenant_id 条件;</li>
* <li>分页插件;</li>
* <li>乐观锁插件。</li>
* </ul>
*/
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
/**
* 分页插件配置
* MyBatis-Plus 主拦截器配置
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
public MybatisPlusInterceptor mybatisPlusInterceptor(TenantLineHandler tenantLineHandler) {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页插件
// 1. 多租户插件(需优先添加)
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(tenantLineHandler));
// 2. 分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 乐观锁插件
// 3. 乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
/**
* 多租户处理器定义如何获取租户ID、租户字段名以及忽略的表
*/
@Bean
public TenantLineHandler tenantLineHandler() {
// 需要忽略多租户的表(不自动拼接 tenant_id
Set<String> ignoreTables = new HashSet<>();
ignoreTables.add("tenant"); // 租户表本身
ignoreTables.add("industry_tags"); // 行业标签(示例:如认为是公共字典)
return new TenantLineHandler() {
@Override
public Expression getTenantId() {
String tenantId = TenantContextHolder.getTenantId();
// 没有租户ID时返回 null 由 MyBatis-Plus 决定处理策略,通常为不过滤或抛错(视版本而定)
return tenantId == null ? null : new StringValue(tenantId);
}
@Override
public String getTenantIdColumn() {
return "tenant_id";
}
@Override
public boolean ignoreTable(String tableName) {
// 忽略名单内的表不做租户隔离
return ignoreTables.contains(tableName);
}
};
}
}

View File

@@ -0,0 +1,41 @@
package com.rj.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.rj.tenant.TenantContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
/**
* MyBatis-Plus 公共字段自动填充处理器
*
* <p>
* 仅负责在插入时为带有 tenantId 字段的实体自动填充当前租户ID<br/>
* 更新时不修改 tenantId确保租户ID一旦写入不可被业务层随意修改。
* </p>
*/
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
private static final String TENANT_FIELD = "tenantId";
@Override
public void insertFill(MetaObject metaObject) {
// 仅在实体中存在 tenantId 字段且当前值为空时进行填充
if (metaObject.hasSetter(TENANT_FIELD)) {
Object currentValue = getFieldValByName(TENANT_FIELD, metaObject);
if (currentValue == null) {
String tenantId = TenantContextHolder.getTenantId();
if (tenantId != null) {
this.strictInsertFill(metaObject, TENANT_FIELD, String.class, tenantId);
}
}
}
}
@Override
public void updateFill(MetaObject metaObject) {
// 不自动更新 tenantId保持租户ID稳定
}
}

View File

@@ -0,0 +1,110 @@
package com.rj.config;
import com.rj.tenant.TenantContextHolder;
import com.rj.entity.sys.User;
import com.rj.service.sys.IUserService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 多租户过滤器:
* <p>
* - 从 HTTP Header 中读取租户IDX-Tenant-Id<br/>
* - 将租户ID写入 {@link TenantContextHolder}<br/>
* - 在请求结束时清理线程变量,避免线程复用造成的串租户问题
* </p>
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class TenantFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(TenantFilter.class);
/**
* Header 名称常量,便于前后端约定与维护
*/
public static final String TENANT_HEADER = "X-Tenant-Id";
/**
* 认证 Header 名,约定为 Bearer Token
*/
public static final String AUTH_HEADER = "Authorization";
private final IUserService userService;
public TenantFilter(IUserService userService) {
this.userService = userService;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String headerTenantId = request.getHeader(TENANT_HEADER);
String finalTenantId = null;
// 1. 从 Authorization 头中解析 token并查出用户的租户ID
String authHeader = request.getHeader(AUTH_HEADER);
String tokenTenantId = null;
if (authHeader != null && !authHeader.isEmpty()) {
String token = extractToken(authHeader);
if (token != null && !token.isEmpty()) {
User user = userService.getUserByToken(token);
if (user != null) {
tokenTenantId = user.getTenantId();
}
}
}
try {
// 2. 计算本次请求实际使用的租户ID并校验一致性
if (tokenTenantId != null && headerTenantId != null && !headerTenantId.isEmpty()
&& !tokenTenantId.equals(headerTenantId)) {
// Header 与 Token 中的租户不一致,记录告警日志(也可以按需直接拒绝请求)
log.warn("Tenant mismatch between token and header. tokenTenantId={}, headerTenantId={}", tokenTenantId, headerTenantId);
}
if (tokenTenantId != null) {
finalTenantId = tokenTenantId;
} else if (headerTenantId != null && !headerTenantId.isEmpty()) {
finalTenantId = headerTenantId;
}
// 设置租户上下文(允许为 null如公共接口或未登录情况
TenantContextHolder.setTenantId(finalTenantId);
filterChain.doFilter(request, response);
} finally {
// 无论请求是否成功,都要清理线程变量
TenantContextHolder.clear();
}
}
/**
* 从 Authorization 头中提取实际的 token 值。
* 支持形如 "Bearer xxx" 或直接传 token 的方式。
*/
private String extractToken(String authHeader) {
if (authHeader == null) {
return null;
}
authHeader = authHeader.trim();
if (authHeader.toLowerCase().startsWith("bearer ")) {
return authHeader.substring(7).trim();
}
return authHeader;
}
}

View File

@@ -35,6 +35,10 @@ public class AudioManagement implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "录音名称")
@TableField("recording_name")
private String recordingName;

View File

@@ -33,6 +33,10 @@ public class AudioManagementStatistics implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "门店ID")
@TableField("dealership_id")
private Long dealershipId;

View File

@@ -28,6 +28,10 @@ public class AudioTextAnalysisFurniture implements Serializable {
@TableId(type = IdType.ASSIGN_UUID)
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "音频管理ID/父级ID")
@TableField("parent_id")
private String parentId;

View File

@@ -28,6 +28,10 @@ public class AudioTextAnalysisSop implements Serializable {
@TableId(type = IdType.ASSIGN_UUID)
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "父IDUUID用于树状结构关联")
@TableField("parent_id")
private String parentId;

View File

@@ -29,6 +29,10 @@ public class CommunicationRecord implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "客户姓名")
@TableField("customer_name")
private String customerName;

View File

@@ -29,6 +29,10 @@ public class CustomerManagement implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "客户姓名")
@TableField("customer_name")
private String customerName;

View File

@@ -21,6 +21,12 @@ public class CustomerProfileAnalysis {
@TableId(type = IdType.ASSIGN_UUID)
private String id;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* AI分析记录ID
*/

View File

@@ -30,6 +30,10 @@ public class Dealership implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "经销商名称")
@TableField("dealership_name")
private String dealershipName;

View File

@@ -28,6 +28,12 @@ public class FaceDetectLog implements Serializable {
@TableId(value = "id", type = IdType.ASSIGN_UUID)
private String id;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 请求ID
*/

View File

@@ -30,6 +30,10 @@ public class ProjectManagement implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "所属经销商ID")
@TableField("dealership_id")
private String dealershipId;

View File

@@ -30,6 +30,10 @@ public class SalesManagement implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "销售名称")
@TableField("sales_name")
private String salesName;

View File

@@ -23,6 +23,12 @@ public class TtsRequestLog {
*/
@TableId(type = IdType.ASSIGN_UUID)
private String id;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 请求时间

View File

@@ -28,6 +28,12 @@ public class VideoImageAnalysis implements Serializable {
@TableId(value = "id", type = IdType.ASSIGN_UUID)
private String id;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 使用的AI模型
*/

View File

@@ -30,6 +30,10 @@ public class VideoManagement implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "视频名称")
@TableField("video_name")
private String videoName;

View File

@@ -27,6 +27,12 @@ public class VideoSynthesisLog {
@TableId(type = IdType.ASSIGN_UUID)
private String id;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 请求ID唯一
*/

View File

@@ -29,6 +29,10 @@ public class YhyAudioUploadLog implements Serializable {
@TableId("id")
private String id;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "文件路径")
@TableField("file_path")
private String filePath;

View File

@@ -33,4 +33,8 @@ public class Role implements Serializable {
@TableField("role_name")
private String roleName;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
}

View File

@@ -30,6 +30,10 @@ public class User implements Serializable {
@TableId("user_id")
private Integer userId;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
@Schema(description = "用户名称")
@TableField("user_name")
private String userName;

View File

@@ -33,4 +33,8 @@ public class UserRole implements Serializable {
@TableField("role_id")
private Integer roleId;
@Schema(description = "租户ID")
@TableField("tenant_id")
private String tenantId;
}

View File

@@ -1,17 +1,40 @@
package com.rj.mapper.sys;
import com.rj.entity.sys.User;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rj.entity.sys.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* <p>
* 用户表 Mapper 接口
* </p>
*
* <p>
* 说明:
* - 登录认证/根据 token 查询用户时,需要跨租户查询用户信息,因此这些方法通过
* {@link InterceptorIgnore} 显式跳过多租户拦截器,不在 SQL 中追加 tenant_id 条件。
* - 其他通过 MyBatis-Plus 内置 CRUD 产生的 SQL 仍然会自动带上 tenant_id 条件。
* </p>
*
* @author 系统生成
* @since 2025-08-07
*/
public interface UserMapper extends BaseMapper<User> {
/**
* 根据用户名查询用户(登录用),不走多租户拦截器。
*/
@InterceptorIgnore(tenantLine = "true")
@Select("SELECT * FROM user WHERE user_name = #{userName} LIMIT 1")
User selectByUserNameIgnoreTenant(@Param("userName") String userName);
/**
* 根据 token 查询用户token 验证、获取当前用户信息),不走多租户拦截器。
*/
@InterceptorIgnore(tenantLine = "true")
@Select("SELECT * FROM user WHERE token = #{token} LIMIT 1")
User selectByTokenIgnoreTenant(@Param("token") String token);
}

View File

@@ -34,6 +34,9 @@ public class LoginResponse {
@Schema(description = "登录时间")
private String loginTime;
@Schema(description = "租户ID")
private String tenantId;
}

View File

@@ -27,8 +27,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
@Override
public LoginResponse login(LoginRequest loginRequest) {
// 根据用户名查询用户
User user = getUserByUserName(loginRequest.getUserName());
// 根据用户名查询用户(登录时不走多租户拦截器)
User user = this.baseMapper.selectByUserNameIgnoreTenant(loginRequest.getUserName());
if (user == null) {
throw new RuntimeException("用户不存在");
@@ -55,12 +55,14 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
loginResponse.setAvatar(user.getAvatar());
loginResponse.setToken(token);
loginResponse.setLoginTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
loginResponse.setTenantId(user.getTenantId());
return loginResponse;
}
@Override
public User getUserByUserName(String userName) {
// 供其他业务使用的通用查询,保持按租户隔离
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUserName, userName);
return this.getOne(queryWrapper);
@@ -68,16 +70,14 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
@Override
public User getUserByToken(String token) {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getToken, token);
return this.getOne(queryWrapper);
// 用于 token 验证等场景,需跨租户查询用户
return this.baseMapper.selectByTokenIgnoreTenant(token);
}
@Override
public User getUserInfoByToken(String token) {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getToken, token);
return this.getOne(queryWrapper);
// 获取用户详细信息,同样使用跨租户查询
return this.baseMapper.selectByTokenIgnoreTenant(token);
}
}

View File

@@ -0,0 +1,50 @@
package com.rj.tenant;
/**
* 多租户上下文持有器用于在当前线程中保存和获取租户ID。
*
* <p>
* 典型使用场景:
* <ul>
* <li>在请求入口(过滤器 / 拦截器)中根据 Header / Token 解析出租户ID并设置</li>
* <li>MyBatis-Plus 的 TenantLineHandler 从此处读取当前租户;</li>
* <li>业务代码中偶尔需要获取当前请求所在的租户。</li>
* </ul>
* 使用完成后务必调用 {@link #clear()} 清理,避免线程复用导致租户串用。
* </p>
*/
public final class TenantContextHolder {
private static final ThreadLocal<String> TENANT_ID_HOLDER = new ThreadLocal<>();
private TenantContextHolder() {
// 工具类,禁止实例化
}
/**
* 设置当前线程的租户ID。
*
* @param tenantId 租户ID允许为 null表示无租户上下文
*/
public static void setTenantId(String tenantId) {
TENANT_ID_HOLDER.set(tenantId);
}
/**
* 获取当前线程的租户ID。
*
* @return 当前租户ID可能为 null
*/
public static String getTenantId() {
return TENANT_ID_HOLDER.get();
}
/**
* 清理当前线程保存的租户ID防止线程复用导致的租户串用。
*/
public static void clear() {
TENANT_ID_HOLDER.remove();
}
}