疯狂的狮子li
2021-08-13 cb13642e85a9d572d6f88f6ce7e3d7b0893dd713
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.ruoyi.oss.factory;
 
import cn.hutool.core.convert.Convert;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.oss.constant.CloudConstant;
import com.ruoyi.oss.enumd.CloudServiceEnumd;
import com.ruoyi.oss.exception.OssException;
import com.ruoyi.oss.properties.CloudStorageProperties;
import com.ruoyi.oss.service.ICloudStorageStrategy;
 
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * 文件上传Factory
 *
 * @author Lion Li
 */
public class OssFactory {
 
    private static RedisCache redisCache;
 
    static {
        OssFactory.redisCache = SpringUtils.getBean(RedisCache.class);
    }
 
    private static final Map<String, ICloudStorageStrategy> SERVICES = new ConcurrentHashMap<>();
 
    public static ICloudStorageStrategy instance() {
        String type = Convert.toStr(redisCache.getCacheObject(CloudConstant.CACHE_CONFIG_KEY));
        if (StringUtils.isEmpty(type)) {
            throw new OssException("文件存储服务类型无法找到!");
        }
        return instance(type);
    }
 
    public static ICloudStorageStrategy instance(String type) {
        ICloudStorageStrategy service = SERVICES.get(type);
        if (service == null) {
            Object json = redisCache.getCacheObject(CloudConstant.SYS_OSS_KEY + type);
            CloudStorageProperties properties = JsonUtils.parseObject(json.toString(), CloudStorageProperties.class);
            String beanName = CloudServiceEnumd.getServiceName(type);
            ICloudStorageStrategy bean = (ICloudStorageStrategy) ReflectUtils.newInstance(CloudServiceEnumd.getServiceClass(type), properties);
            SpringUtils.registerBean(beanName, bean);
            service = SpringUtils.getBean(beanName);
            SERVICES.put(type, bean);
        }
        return service;
    }
 
    public static void destroy(String type) {
        ICloudStorageStrategy service = SERVICES.get(type);
        if (service == null) {
            return;
        }
        SpringUtils.unregisterBean(CloudServiceEnumd.getServiceName(type));
        SERVICES.remove(type);
    }
 
}