forked from dyf/fys-Multi-tenant
fys
This commit is contained in:
32
fys-common/fys-common-tenant/pom.xml
Normal file
32
fys-common/fys-common-tenant/pom.xml
Normal file
@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>com.fuyuanshen</groupId>
|
||||
<artifactId>fys-common</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>fys-common-tenant</artifactId>
|
||||
|
||||
<description>
|
||||
fys-common-tenant 租户模块
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fuyuanshen</groupId>
|
||||
<artifactId>fys-common-mybatis</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fuyuanshen</groupId>
|
||||
<artifactId>fys-common-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -0,0 +1,86 @@
|
||||
package com.fuyuanshen.common.tenant.config;
|
||||
|
||||
import cn.dev33.satoken.dao.SaTokenDao;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
||||
import com.fuyuanshen.common.core.utils.reflect.ReflectUtils;
|
||||
import com.fuyuanshen.common.redis.config.RedisConfig;
|
||||
import com.fuyuanshen.common.redis.config.properties.RedissonProperties;
|
||||
import com.fuyuanshen.common.tenant.core.TenantSaTokenDao;
|
||||
import com.fuyuanshen.common.tenant.handle.PlusTenantLineHandler;
|
||||
import com.fuyuanshen.common.tenant.handle.TenantKeyPrefixHandler;
|
||||
import com.fuyuanshen.common.tenant.manager.TenantSpringCacheManager;
|
||||
import com.fuyuanshen.common.tenant.properties.TenantProperties;
|
||||
import org.redisson.config.ClusterServersConfig;
|
||||
import org.redisson.config.SingleServerConfig;
|
||||
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
/**
|
||||
* 租户配置类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@EnableConfigurationProperties(TenantProperties.class)
|
||||
@AutoConfiguration(after = {RedisConfig.class})
|
||||
@ConditionalOnProperty(value = "tenant.enable", havingValue = "true")
|
||||
public class TenantConfig {
|
||||
|
||||
@ConditionalOnClass(TenantLineInnerInterceptor.class)
|
||||
@AutoConfiguration
|
||||
static class MybatisPlusConfiguration {
|
||||
|
||||
/**
|
||||
* 多租户插件
|
||||
*/
|
||||
@Bean
|
||||
public TenantLineInnerInterceptor tenantLineInnerInterceptor(TenantProperties tenantProperties) {
|
||||
return new TenantLineInnerInterceptor(new PlusTenantLineHandler(tenantProperties));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedissonAutoConfigurationCustomizer tenantRedissonCustomizer(RedissonProperties redissonProperties) {
|
||||
return config -> {
|
||||
TenantKeyPrefixHandler nameMapper = new TenantKeyPrefixHandler(redissonProperties.getKeyPrefix());
|
||||
SingleServerConfig singleServerConfig = ReflectUtils.invokeGetter(config, "singleServerConfig");
|
||||
if (ObjectUtil.isNotNull(singleServerConfig)) {
|
||||
// 使用单机模式
|
||||
// 设置多租户 redis key前缀
|
||||
singleServerConfig.setNameMapper(nameMapper);
|
||||
}
|
||||
ClusterServersConfig clusterServersConfig = ReflectUtils.invokeGetter(config, "clusterServersConfig");
|
||||
// 集群配置方式 参考下方注释
|
||||
if (ObjectUtil.isNotNull(clusterServersConfig)) {
|
||||
// 设置多租户 redis key前缀
|
||||
clusterServersConfig.setNameMapper(nameMapper);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 多租户缓存管理器
|
||||
*/
|
||||
@Primary
|
||||
@Bean
|
||||
public CacheManager tenantCacheManager() {
|
||||
return new TenantSpringCacheManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* 多租户鉴权dao实现
|
||||
*/
|
||||
@Primary
|
||||
@Bean
|
||||
public SaTokenDao tenantSaTokenDao() {
|
||||
return new TenantSaTokenDao();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.fuyuanshen.common.tenant.core;
|
||||
|
||||
import com.fuyuanshen.common.mybatis.core.domain.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* 租户基类
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class TenantEntity extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 租户编号
|
||||
*/
|
||||
private String tenantId;
|
||||
|
||||
}
|
@ -0,0 +1,158 @@
|
||||
package com.fuyuanshen.common.tenant.core;
|
||||
|
||||
import com.fuyuanshen.common.core.constant.GlobalConstants;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import com.fuyuanshen.common.satoken.core.dao.PlusSaTokenDao;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* SaToken 认证数据持久层 适配多租户
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public class TenantSaTokenDao extends PlusSaTokenDao {
|
||||
|
||||
@Override
|
||||
public String get(String key) {
|
||||
return super.get(GlobalConstants.GLOBAL_REDIS_KEY + key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(String key, String value, long timeout) {
|
||||
super.set(GlobalConstants.GLOBAL_REDIS_KEY + key, value, timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修修改指定key-value键值对 (过期时间不变)
|
||||
*/
|
||||
@Override
|
||||
public void update(String key, String value) {
|
||||
long expire = getTimeout(key);
|
||||
// -2 = 无此键
|
||||
if (expire == NOT_VALUE_EXPIRE) {
|
||||
return;
|
||||
}
|
||||
this.set(key, value, expire);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除Value
|
||||
*/
|
||||
@Override
|
||||
public void delete(String key) {
|
||||
super.delete(GlobalConstants.GLOBAL_REDIS_KEY + key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Value的剩余存活时间 (单位: 秒)
|
||||
*/
|
||||
@Override
|
||||
public long getTimeout(String key) {
|
||||
return super.getTimeout(GlobalConstants.GLOBAL_REDIS_KEY + key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改Value的剩余存活时间 (单位: 秒)
|
||||
*/
|
||||
@Override
|
||||
public void updateTimeout(String key, long timeout) {
|
||||
// 判断是否想要设置为永久
|
||||
if (timeout == NEVER_EXPIRE) {
|
||||
long expire = getTimeout(key);
|
||||
if (expire == NEVER_EXPIRE) {
|
||||
// 如果其已经被设置为永久,则不作任何处理
|
||||
} else {
|
||||
// 如果尚未被设置为永久,那么再次set一次
|
||||
this.set(key, this.get(key), timeout);
|
||||
}
|
||||
return;
|
||||
}
|
||||
RedisUtils.expire(GlobalConstants.GLOBAL_REDIS_KEY + key, Duration.ofSeconds(timeout));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取Object,如无返空
|
||||
*/
|
||||
@Override
|
||||
public Object getObject(String key) {
|
||||
return super.getObject(GlobalConstants.GLOBAL_REDIS_KEY + key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Object (指定反序列化类型),如无返空
|
||||
*
|
||||
* @param key 键名称
|
||||
* @return object
|
||||
*/
|
||||
@Override
|
||||
public <T> T getObject(String key, Class<T> classType) {
|
||||
return super.getObject(GlobalConstants.GLOBAL_REDIS_KEY + key, classType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入Object,并设定存活时间 (单位: 秒)
|
||||
*/
|
||||
@Override
|
||||
public void setObject(String key, Object object, long timeout) {
|
||||
super.setObject(GlobalConstants.GLOBAL_REDIS_KEY + key, object, timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新Object (过期时间不变)
|
||||
*/
|
||||
@Override
|
||||
public void updateObject(String key, Object object) {
|
||||
long expire = getObjectTimeout(key);
|
||||
// -2 = 无此键
|
||||
if (expire == NOT_VALUE_EXPIRE) {
|
||||
return;
|
||||
}
|
||||
this.setObject(key, object, expire);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除Object
|
||||
*/
|
||||
@Override
|
||||
public void deleteObject(String key) {
|
||||
super.deleteObject(GlobalConstants.GLOBAL_REDIS_KEY + key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Object的剩余存活时间 (单位: 秒)
|
||||
*/
|
||||
@Override
|
||||
public long getObjectTimeout(String key) {
|
||||
return super.getObjectTimeout(GlobalConstants.GLOBAL_REDIS_KEY + key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改Object的剩余存活时间 (单位: 秒)
|
||||
*/
|
||||
@Override
|
||||
public void updateObjectTimeout(String key, long timeout) {
|
||||
// 判断是否想要设置为永久
|
||||
if (timeout == NEVER_EXPIRE) {
|
||||
long expire = getObjectTimeout(key);
|
||||
if (expire == NEVER_EXPIRE) {
|
||||
// 如果其已经被设置为永久,则不作任何处理
|
||||
} else {
|
||||
// 如果尚未被设置为永久,那么再次set一次
|
||||
this.setObject(key, this.getObject(key), timeout);
|
||||
}
|
||||
return;
|
||||
}
|
||||
RedisUtils.expire(GlobalConstants.GLOBAL_REDIS_KEY + key, Duration.ofSeconds(timeout));
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索数据
|
||||
*/
|
||||
@Override
|
||||
public List<String> searchData(String prefix, String keyword, int start, int size, boolean sortType) {
|
||||
return super.searchData(GlobalConstants.GLOBAL_REDIS_KEY + prefix, keyword, start, size, sortType);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.fuyuanshen.common.tenant.exception;
|
||||
|
||||
import com.fuyuanshen.common.core.exception.base.BaseException;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 租户异常类
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public class TenantException extends BaseException {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public TenantException(String code, Object... args) {
|
||||
super("tenant", code, args, null);
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.fuyuanshen.common.tenant.handle;
|
||||
|
||||
import cn.hutool.core.collection.ListUtil;
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.sf.jsqlparser.expression.Expression;
|
||||
import net.sf.jsqlparser.expression.NullValue;
|
||||
import net.sf.jsqlparser.expression.StringValue;
|
||||
import com.fuyuanshen.common.core.utils.StringUtils;
|
||||
import com.fuyuanshen.common.tenant.helper.TenantHelper;
|
||||
import com.fuyuanshen.common.tenant.properties.TenantProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 自定义租户处理器
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
public class PlusTenantLineHandler implements TenantLineHandler {
|
||||
|
||||
private final TenantProperties tenantProperties;
|
||||
|
||||
@Override
|
||||
public Expression getTenantId() {
|
||||
String tenantId = TenantHelper.getTenantId();
|
||||
if (StringUtils.isBlank(tenantId)) {
|
||||
log.error("无法获取有效的租户id -> Null");
|
||||
return new NullValue();
|
||||
}
|
||||
// 返回固定租户
|
||||
return new StringValue(tenantId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ignoreTable(String tableName) {
|
||||
String tenantId = TenantHelper.getTenantId();
|
||||
// 判断是否有租户
|
||||
if (StringUtils.isNotBlank(tenantId)) {
|
||||
// 不需要过滤租户的表
|
||||
List<String> excludes = tenantProperties.getExcludes();
|
||||
// 非业务表
|
||||
List<String> tables = ListUtil.toList(
|
||||
"gen_table",
|
||||
"gen_table_column"
|
||||
);
|
||||
tables.addAll(excludes);
|
||||
return StringUtils.containsAnyIgnoreCase(tableName, tables.toArray(new String[0]));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
package com.fuyuanshen.common.tenant.handle;
|
||||
|
||||
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.fuyuanshen.common.core.constant.GlobalConstants;
|
||||
import com.fuyuanshen.common.core.utils.StringUtils;
|
||||
import com.fuyuanshen.common.redis.handler.KeyPrefixHandler;
|
||||
import com.fuyuanshen.common.tenant.helper.TenantHelper;
|
||||
|
||||
/**
|
||||
* 多租户redis缓存key前缀处理
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
public class TenantKeyPrefixHandler extends KeyPrefixHandler {
|
||||
|
||||
public TenantKeyPrefixHandler(String keyPrefix) {
|
||||
super(keyPrefix);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加前缀
|
||||
*/
|
||||
@Override
|
||||
public String map(String name) {
|
||||
if (StringUtils.isBlank(name)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (InterceptorIgnoreHelper.willIgnoreTenantLine("")) {
|
||||
return super.map(name);
|
||||
}
|
||||
} catch (NoClassDefFoundError ignore) {
|
||||
// 有些服务不需要mp导致类不存在 忽略即可
|
||||
}
|
||||
if (StringUtils.contains(name, GlobalConstants.GLOBAL_REDIS_KEY)) {
|
||||
return super.map(name);
|
||||
}
|
||||
String tenantId = TenantHelper.getTenantId();
|
||||
if (StringUtils.isBlank(tenantId)) {
|
||||
log.debug("无法获取有效的租户id -> Null");
|
||||
return super.map(name);
|
||||
}
|
||||
if (StringUtils.startsWith(name, tenantId + "")) {
|
||||
// 如果存在则直接返回
|
||||
return super.map(name);
|
||||
}
|
||||
return super.map(tenantId + ":" + name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去除前缀
|
||||
*/
|
||||
@Override
|
||||
public String unmap(String name) {
|
||||
String unmap = super.unmap(name);
|
||||
if (StringUtils.isBlank(unmap)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (InterceptorIgnoreHelper.willIgnoreTenantLine("")) {
|
||||
return unmap;
|
||||
}
|
||||
} catch (NoClassDefFoundError ignore) {
|
||||
// 有些服务不需要mp导致类不存在 忽略即可
|
||||
}
|
||||
if (StringUtils.contains(name, GlobalConstants.GLOBAL_REDIS_KEY)) {
|
||||
return unmap;
|
||||
}
|
||||
String tenantId = TenantHelper.getTenantId();
|
||||
if (StringUtils.isBlank(tenantId)) {
|
||||
log.debug("无法获取有效的租户id -> Null");
|
||||
return unmap;
|
||||
}
|
||||
if (StringUtils.startsWith(unmap, tenantId + "")) {
|
||||
// 如果存在则删除
|
||||
return unmap.substring((tenantId + ":").length());
|
||||
}
|
||||
return unmap;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,231 @@
|
||||
package com.fuyuanshen.common.tenant.helper;
|
||||
|
||||
import cn.dev33.satoken.context.SaHolder;
|
||||
import cn.dev33.satoken.context.model.SaStorage;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy;
|
||||
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.fuyuanshen.common.core.constant.GlobalConstants;
|
||||
import com.fuyuanshen.common.core.utils.SpringUtils;
|
||||
import com.fuyuanshen.common.core.utils.StringUtils;
|
||||
import com.fuyuanshen.common.core.utils.reflect.ReflectUtils;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import com.fuyuanshen.common.satoken.utils.LoginHelper;
|
||||
|
||||
import java.util.Stack;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* 租户助手
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class TenantHelper {
|
||||
|
||||
private static final String DYNAMIC_TENANT_KEY = GlobalConstants.GLOBAL_REDIS_KEY + "dynamicTenant";
|
||||
|
||||
private static final ThreadLocal<String> TEMP_DYNAMIC_TENANT = new ThreadLocal<>();
|
||||
|
||||
private static final ThreadLocal<Stack<Integer>> REENTRANT_IGNORE = ThreadLocal.withInitial(Stack::new);
|
||||
|
||||
/**
|
||||
* 租户功能是否启用
|
||||
*/
|
||||
public static boolean isEnable() {
|
||||
return Convert.toBool(SpringUtils.getProperty("tenant.enable"), false);
|
||||
}
|
||||
|
||||
private static IgnoreStrategy getIgnoreStrategy() {
|
||||
Object ignoreStrategyLocal = ReflectUtils.getStaticFieldValue(ReflectUtils.getField(InterceptorIgnoreHelper.class, "IGNORE_STRATEGY_LOCAL"));
|
||||
if (ignoreStrategyLocal instanceof ThreadLocal<?> IGNORE_STRATEGY_LOCAL) {
|
||||
if (IGNORE_STRATEGY_LOCAL.get() instanceof IgnoreStrategy ignoreStrategy) {
|
||||
return ignoreStrategy;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启忽略租户(开启后需手动调用 {@link #disableIgnore()} 关闭)
|
||||
*/
|
||||
public static void enableIgnore() {
|
||||
IgnoreStrategy ignoreStrategy = getIgnoreStrategy();
|
||||
if (ObjectUtil.isNull(ignoreStrategy)) {
|
||||
InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().tenantLine(true).build());
|
||||
} else {
|
||||
ignoreStrategy.setTenantLine(true);
|
||||
}
|
||||
Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
|
||||
reentrantStack.push(reentrantStack.size() + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭忽略租户
|
||||
*/
|
||||
public static void disableIgnore() {
|
||||
IgnoreStrategy ignoreStrategy = getIgnoreStrategy();
|
||||
if (ObjectUtil.isNotNull(ignoreStrategy)) {
|
||||
boolean noOtherIgnoreStrategy = !Boolean.TRUE.equals(ignoreStrategy.getDynamicTableName())
|
||||
&& !Boolean.TRUE.equals(ignoreStrategy.getBlockAttack())
|
||||
&& !Boolean.TRUE.equals(ignoreStrategy.getIllegalSql())
|
||||
&& !Boolean.TRUE.equals(ignoreStrategy.getDataPermission())
|
||||
&& CollectionUtil.isEmpty(ignoreStrategy.getOthers());
|
||||
Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
|
||||
boolean empty = reentrantStack.isEmpty() || reentrantStack.pop() == 1;
|
||||
if (noOtherIgnoreStrategy && empty) {
|
||||
InterceptorIgnoreHelper.clearIgnoreStrategy();
|
||||
} else if (empty) {
|
||||
ignoreStrategy.setTenantLine(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在忽略租户中执行
|
||||
*
|
||||
* @param handle 处理执行方法
|
||||
*/
|
||||
public static void ignore(Runnable handle) {
|
||||
enableIgnore();
|
||||
try {
|
||||
handle.run();
|
||||
} finally {
|
||||
disableIgnore();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在忽略租户中执行
|
||||
*
|
||||
* @param handle 处理执行方法
|
||||
*/
|
||||
public static <T> T ignore(Supplier<T> handle) {
|
||||
enableIgnore();
|
||||
try {
|
||||
return handle.get();
|
||||
} finally {
|
||||
disableIgnore();
|
||||
}
|
||||
}
|
||||
|
||||
public static void setDynamic(String tenantId) {
|
||||
setDynamic(tenantId, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置动态租户(一直有效 需要手动清理)
|
||||
* <p>
|
||||
* 如果为未登录状态下 那么只在当前线程内生效
|
||||
*
|
||||
* @param tenantId 租户id
|
||||
* @param global 是否全局生效
|
||||
*/
|
||||
public static void setDynamic(String tenantId, boolean global) {
|
||||
if (!isEnable()) {
|
||||
return;
|
||||
}
|
||||
if (!LoginHelper.isLogin() || !global) {
|
||||
TEMP_DYNAMIC_TENANT.set(tenantId);
|
||||
return;
|
||||
}
|
||||
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
|
||||
RedisUtils.setCacheObject(cacheKey, tenantId);
|
||||
SaHolder.getStorage().set(cacheKey, tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取动态租户(一直有效 需要手动清理)
|
||||
* <p>
|
||||
* 如果为未登录状态下 那么只在当前线程内生效
|
||||
*/
|
||||
public static String getDynamic() {
|
||||
if (!isEnable()) {
|
||||
return null;
|
||||
}
|
||||
if (!LoginHelper.isLogin()) {
|
||||
return TEMP_DYNAMIC_TENANT.get();
|
||||
}
|
||||
// 如果线程内有值 优先返回
|
||||
String tenantId = TEMP_DYNAMIC_TENANT.get();
|
||||
if (StringUtils.isNotBlank(tenantId)) {
|
||||
return tenantId;
|
||||
}
|
||||
SaStorage storage = SaHolder.getStorage();
|
||||
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
|
||||
tenantId = storage.getString(cacheKey);
|
||||
// 如果为 -1 说明已经查过redis并且不存在值 则直接返回null
|
||||
if (StringUtils.isNotBlank(tenantId)) {
|
||||
return tenantId.equals("-1") ? null : tenantId;
|
||||
}
|
||||
tenantId = RedisUtils.getCacheObject(cacheKey);
|
||||
storage.set(cacheKey, StringUtils.isBlank(tenantId) ? "-1" : tenantId);
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除动态租户
|
||||
*/
|
||||
public static void clearDynamic() {
|
||||
if (!isEnable()) {
|
||||
return;
|
||||
}
|
||||
if (!LoginHelper.isLogin()) {
|
||||
TEMP_DYNAMIC_TENANT.remove();
|
||||
return;
|
||||
}
|
||||
TEMP_DYNAMIC_TENANT.remove();
|
||||
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
|
||||
RedisUtils.deleteObject(cacheKey);
|
||||
SaHolder.getStorage().delete(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在动态租户中执行
|
||||
*
|
||||
* @param handle 处理执行方法
|
||||
*/
|
||||
public static void dynamic(String tenantId, Runnable handle) {
|
||||
setDynamic(tenantId);
|
||||
try {
|
||||
handle.run();
|
||||
} finally {
|
||||
clearDynamic();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在动态租户中执行
|
||||
*
|
||||
* @param handle 处理执行方法
|
||||
*/
|
||||
public static <T> T dynamic(String tenantId, Supplier<T> handle) {
|
||||
setDynamic(tenantId);
|
||||
try {
|
||||
return handle.get();
|
||||
} finally {
|
||||
clearDynamic();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前租户id(动态租户优先)
|
||||
*/
|
||||
public static String getTenantId() {
|
||||
if (!isEnable()) {
|
||||
return null;
|
||||
}
|
||||
String tenantId = TenantHelper.getDynamic();
|
||||
if (StringUtils.isBlank(tenantId)) {
|
||||
tenantId = LoginHelper.getTenantId();
|
||||
}
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.fuyuanshen.common.tenant.manager;
|
||||
|
||||
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.fuyuanshen.common.core.constant.GlobalConstants;
|
||||
import com.fuyuanshen.common.core.utils.StringUtils;
|
||||
import com.fuyuanshen.common.redis.manager.PlusSpringCacheManager;
|
||||
import com.fuyuanshen.common.tenant.helper.TenantHelper;
|
||||
import org.springframework.cache.Cache;
|
||||
|
||||
/**
|
||||
* 重写 cacheName 处理方法 支持多租户
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
public class TenantSpringCacheManager extends PlusSpringCacheManager {
|
||||
|
||||
public TenantSpringCacheManager() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cache getCache(String name) {
|
||||
if (InterceptorIgnoreHelper.willIgnoreTenantLine("")) {
|
||||
return super.getCache(name);
|
||||
}
|
||||
if (StringUtils.contains(name, GlobalConstants.GLOBAL_REDIS_KEY)) {
|
||||
return super.getCache(name);
|
||||
}
|
||||
String tenantId = TenantHelper.getTenantId();
|
||||
if (StringUtils.isBlank(tenantId)) {
|
||||
log.error("无法获取有效的租户id -> Null");
|
||||
}
|
||||
if (StringUtils.startsWith(name, tenantId)) {
|
||||
// 如果存在则直接返回
|
||||
return super.getCache(name);
|
||||
}
|
||||
return super.getCache(tenantId + ":" + name);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.fuyuanshen.common.tenant.properties;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 租户 配置属性
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "tenant")
|
||||
public class TenantProperties {
|
||||
|
||||
/**
|
||||
* 是否启用
|
||||
*/
|
||||
private Boolean enable;
|
||||
|
||||
/**
|
||||
* 排除表
|
||||
*/
|
||||
private List<String> excludes;
|
||||
|
||||
}
|
@ -0,0 +1 @@
|
||||
com.fuyuanshen.common.tenant.config.TenantConfig
|
Reference in New Issue
Block a user