【7.3.2】【cache】租户缓存动态代理类

pull/41/head
fengshuonan 2022-11-08 01:09:08 +08:00
parent 7c53c9a4a0
commit f4bd3d6d15
2 changed files with 102 additions and 0 deletions

View File

@ -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();
}
}

View File

@ -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;
}
}