优化 OssFactory,采用双重校验锁

This commit is contained in:
数据小王子 2024-03-01 15:29:44 +08:00
parent 3bedaa7ddc
commit 62c8e1c877
2 changed files with 18 additions and 11 deletions

View File

@ -13,6 +13,7 @@ import lombok.extern.slf4j.Slf4j;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/** /**
* 文件上传Factory * 文件上传Factory
@ -23,6 +24,7 @@ import java.util.concurrent.ConcurrentHashMap;
public class OssFactory { public class OssFactory {
private static final Map<String, OssClient> CLIENT_CACHE = new ConcurrentHashMap<>(); private static final Map<String, OssClient> CLIENT_CACHE = new ConcurrentHashMap<>();
private static final ReentrantLock LOCK = new ReentrantLock();
/** /**
* 获取默认实例 * 获取默认实例
@ -39,7 +41,7 @@ public class OssFactory {
/** /**
* 根据类型获取实例 * 根据类型获取实例
*/ */
public static synchronized OssClient instance(String configKey) { public static OssClient instance(String configKey) {
String json = CacheUtils.get(CacheNames.SYS_OSS_CONFIG, configKey); String json = CacheUtils.get(CacheNames.SYS_OSS_CONFIG, configKey);
if (json == null) { if (json == null) {
throw new OssException("系统异常, '" + configKey + "'配置信息不存在!"); throw new OssException("系统异常, '" + configKey + "'配置信息不存在!");
@ -48,16 +50,19 @@ public class OssFactory {
// 使用租户标识避免多个租户相同key实例覆盖 // 使用租户标识避免多个租户相同key实例覆盖
String key = properties.getTenantId() + ":" + configKey; String key = properties.getTenantId() + ":" + configKey;
OssClient client = CLIENT_CACHE.get(key); OssClient client = CLIENT_CACHE.get(key);
if (client == null) { // 客户端不存在或配置不相同则重新构建
CLIENT_CACHE.put(key, new OssClient(configKey, properties)); if (client == null || !client.checkPropertiesSame(properties)) {
log.info("创建OSS实例 key => {}", configKey); LOCK.lock();
return CLIENT_CACHE.get(key); try {
} client = CLIENT_CACHE.get(key);
// 配置不相同则重新构建 if (client == null || !client.checkPropertiesSame(properties)) {
if (!client.checkPropertiesSame(properties)) { CLIENT_CACHE.put(key, new OssClient(configKey, properties));
CLIENT_CACHE.put(key, new OssClient(configKey, properties)); log.info("创建OSS实例 key => {}", configKey);
log.info("重载OSS实例 key => {}", configKey); return CLIENT_CACHE.get(key);
return CLIENT_CACHE.get(key); }
} finally {
LOCK.unlock();
}
} }
return client; return client;
} }

View File

@ -5,12 +5,14 @@ import com.mybatisflex.core.tenant.TenantFactory;
import com.ruoyi.common.security.utils.LoginHelper; import com.ruoyi.common.security.utils.LoginHelper;
import com.ruoyi.common.tenant.helper.TenantHelper; import com.ruoyi.common.tenant.helper.TenantHelper;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/** /**
* 自定义租户工厂 * 自定义租户工厂
* *
* @author 数据小王子 * @author 数据小王子
*/ */
@Slf4j
@AllArgsConstructor @AllArgsConstructor
public class MyTenantFactory implements TenantFactory { public class MyTenantFactory implements TenantFactory {