mirror of https://gitee.com/stylefeng/roses
【7.3.2】【cache】租户缓存动态代理类
parent
7c53c9a4a0
commit
f4bd3d6d15
|
@ -0,0 +1,43 @@
|
|||
package cn.stylefeng.roses.kernel.rule.tenant;
|
||||
|
||||
/**
|
||||
* 租户编码信息暂存,一般给缓存使用
|
||||
*
|
||||
* @author fengshuonan
|
||||
* @date 2022/11/8 0:58
|
||||
*/
|
||||
public class TenantCodeHolder {
|
||||
|
||||
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
|
||||
|
||||
/**
|
||||
* 设置租户编码
|
||||
*
|
||||
* @author fengshuonan
|
||||
* @date 2022/11/8 0:59
|
||||
*/
|
||||
public static void setTenantCode(String aesKey) {
|
||||
CONTEXT_HOLDER.set(aesKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取租户编码
|
||||
*
|
||||
* @author fengshuonan
|
||||
* @date 2022/11/8 0:59
|
||||
*/
|
||||
public static String getTenantCode() {
|
||||
return CONTEXT_HOLDER.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除租户编码
|
||||
*
|
||||
* @author fengshuonan
|
||||
* @date 2022/11/8 0:59
|
||||
*/
|
||||
public static void clearTenantCode() {
|
||||
CONTEXT_HOLDER.remove();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package cn.stylefeng.roses.kernel.cache.api.tenant;
|
||||
|
||||
import cn.stylefeng.roses.kernel.cache.api.CacheOperatorApi;
|
||||
import cn.stylefeng.roses.kernel.rule.tenant.TenantCodeHolder;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* 租户缓存动态代理
|
||||
*
|
||||
* @author fengshuonan
|
||||
* @date 2022/11/8 0:45
|
||||
*/
|
||||
@SuppressWarnings("all")
|
||||
public class TenantCacheProxy<T> implements InvocationHandler {
|
||||
|
||||
/**
|
||||
* 被代理的缓存操作类
|
||||
*/
|
||||
private CacheOperatorApi<T> targetCacheObject = null;
|
||||
|
||||
/**
|
||||
* 租户编码
|
||||
*/
|
||||
private String tenantCode = null;
|
||||
|
||||
/**
|
||||
* 绑定缓存操作原始类
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param target 被代理的缓存类
|
||||
* @author fengshuonan
|
||||
* @date 2022/11/8 1:05
|
||||
*/
|
||||
public CacheOperatorApi<T> bindCacheObject(String tenantCode, CacheOperatorApi<T> target) {
|
||||
this.targetCacheObject = target;
|
||||
this.tenantCode = tenantCode;
|
||||
return (CacheOperatorApi<T>) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
Object result = null;
|
||||
try {
|
||||
// 设置租户编码
|
||||
TenantCodeHolder.setTenantCode(tenantCode);
|
||||
|
||||
// 执行原有缓存操作类
|
||||
result = method.invoke(targetCacheObject, args);
|
||||
} finally {
|
||||
// 清除租户编码
|
||||
TenantCodeHolder.clearTenantCode();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue