6 changed files with 72 additions and 89 deletions
@ -1,60 +0,0 @@ |
|||||||
package com.cloud.kicc.common.data.util; |
|
||||||
|
|
||||||
import cn.hutool.core.util.ObjectUtil; |
|
||||||
import cn.hutool.core.util.StrUtil; |
|
||||||
import com.cloud.kicc.common.data.entity.KiccUser; |
|
||||||
import com.cloud.kicc.common.data.override.TenantLikeExpression; |
|
||||||
import lombok.experimental.UtilityClass; |
|
||||||
import org.springframework.security.core.Authentication; |
|
||||||
import org.springframework.security.core.context.SecurityContextHolder; |
|
||||||
|
|
||||||
import java.util.Optional; |
|
||||||
import java.util.concurrent.atomic.AtomicReference; |
|
||||||
|
|
||||||
/** |
|
||||||
*<p> |
|
||||||
* 动态设置多租户 |
|
||||||
*</p> |
|
||||||
* |
|
||||||
* @Author: entfrm开发团队-王翔 |
|
||||||
* @Date: 2022/5/13 |
|
||||||
*/ |
|
||||||
@UtilityClass |
|
||||||
public class TenantContextHolder { |
|
||||||
|
|
||||||
private final ThreadLocal<String> contextHolder = new ThreadLocal(); |
|
||||||
|
|
||||||
public void setTenant(String tenantIds) { |
|
||||||
contextHolder.set(tenantIds); |
|
||||||
} |
|
||||||
|
|
||||||
public String getTenant() { |
|
||||||
String tenantIds = ObjectUtil.isNotEmpty(getUser()) ? getUser().getTenantId() : clearTenant(); |
|
||||||
return StrUtil.isNotBlank(contextHolder.get()) ? contextHolder.get() : tenantIds; |
|
||||||
} |
|
||||||
|
|
||||||
/** |
|
||||||
* 校验用户多租户是否为空,为空说明当前用户未登录,需要清除当前线程多租户数据 |
|
||||||
* 不收的销毁,会出现 ThreadLocal 内存泄漏的问题 |
|
||||||
*/ |
|
||||||
public String clearTenant() { |
|
||||||
contextHolder.remove(); |
|
||||||
return null; |
|
||||||
} |
|
||||||
|
|
||||||
/** |
|
||||||
* 获取用户 |
|
||||||
* 如果当前不存在用户,正常情况多租户拼接查询会报错 |
|
||||||
*/ |
|
||||||
private KiccUser getUser() { |
|
||||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
|
||||||
if (Optional.ofNullable(authentication).isPresent()) { |
|
||||||
Object principal = authentication.getPrincipal(); |
|
||||||
if (principal instanceof KiccUser) { |
|
||||||
return (KiccUser) principal; |
|
||||||
} |
|
||||||
} |
|
||||||
return null; |
|
||||||
} |
|
||||||
|
|
||||||
} |
|
Loading…
Reference in new issue