美文网首页
缓存与单例

缓存与单例

作者: 以梦为马驾驾驾 | 来源:发表于2024-01-10 12:42 被阅读0次

分析这部分代码:涉及哪些高并发的问题

    private Cache<StringWrapper, AtomicReference<ConfigClient>> mtConfigClientCache = CacheBuilder.newBuilder()
            .expireAfterWrite(7, TimeUnit.DAYS)
            .maximumSize(2000)
            .build();
    private final Map<String, StringWrapper> key2LockKey = new ConcurrentHashMap<String, StringWrapper>();

    private LoadingCache<String, MtConfigClient> mtConfigClientLoadingCache = CacheBuilder.newBuilder()
            .expireAfterWrite(7, TimeUnit.DAYS)
            .maximumSize(2000)
            .build(new CacheLoader<String, MtConfigClient>() {
                @Override
                public ConfigClient load(String key) throws Exception {
                    return buildClient(key);
                }
            });

    private ConfigClient getMccClient(String appKey) {
        return this.getMccClientByLoader(appKey);
    }

    private ConfigClient getMccClient2(String appKey) {
        final StringWrapper appKeyLock = key2LockKey.computeIfAbsent(appKey, StringWrapper::new);
        // appKey should not be used again,we force appKey = null to remind others here
        appKey = null;
        AtomicReference<MtConfigClient> mtConfigClientAtomicReference = mtConfigClientCache.getIfPresent(appKeyLock);
        if (mtConfigClientAtomicReference == null) { // mtConfigClientAtomicReference.get() == null, we wont allow this happen
            synchronized (appKeyLock) {
                mtConfigClientAtomicReference = mtConfigClientCache.getIfPresent(appKeyLock);
                if (mtConfigClientAtomicReference == null) {
                    try {
                        MtConfigClient mtConfigClientCreating = new MtConfigClient();
                        mtConfigClientCreating.setAppkey(appKeyLock.s);
                        mtConfigClientCreating.setModel("v2");
                        mtConfigClientCreating.setId("UpdateRateLimitConfig_" + System.nanoTime());
                        mtConfigClientCreating.init();
                        mtConfigClientAtomicReference = new AtomicReference<>();
                        mtConfigClientAtomicReference.set(mtConfigClientCreating);
                        this.mtConfigClientCache.put(appKeyLock, mtConfigClientAtomicReference);
                    } catch (Exception ex) {
                        LOGGER.info("mcc客户端初始化失败:", ex);
                    }
                }
            }
        }
        return Optional.ofNullable(this.mtConfigClientCache.getIfPresent(appKeyLock))
                .orElseGet(() -> null)
                .get();
    }

    private MtConfigClient getMccClientByLoader(String appKey) {
        try {
            return this.mtConfigClientLoadingCache.get(appKey);
        } catch (ExecutionException e) {
            LOGGER.error("获取mcc客户端失败", e);
            return null;
        }
    }

    private MtConfigClient buildMccClient(String appKey) {
        try {
            MtConfigClient mtConfigClientCreating = new MtConfigClient();
            mtConfigClientCreating.setAppkey(appKey);
            mtConfigClientCreating.setModel("v2");
            mtConfigClientCreating.setId("UpdateRateLimitConfig_" + System.nanoTime());
            mtConfigClientCreating.init();
            return mtConfigClientCreating;
        }catch (Exception ex) {
            LOGGER.error("mcc客户端初始化失败:", ex);
            throw ex;
        }
    }


    static class StringWrapper {
        public String s;
        public StringWrapper(String s) {
            this.s = s;
        }
    }

这已经是修改后的代码,原先的代码有单例模式的典型错误,在将 client 放到cache之前,在做init操作,但是init操作耗时较长,约9s。这就导致其他线程拿到的是,未初始化完成的client。

这里的修改优化一个是: 使用 LoadingCache,这是单线程加载的,有他就够了。
如果不想用cache,第二种优化方式是:
final StringWrapper appKeyLock = key2LockKey.computeIfAbsent(appKey, StringWrapper::new);
想要针对每个key来创建单例,可以把他们转化到同一个对象,同时,使用AtomicReference<MtConfigClient> 来保证init方法一定会执行完之后,才会执行放到map里,对其他线程可见,因为AtomicReference的内部值引用是 volatile,有防止重排序的语意。

相关文章

网友评论

      本文标题:缓存与单例

      本文链接:https://www.haomeiwen.com/subject/cggxndtx.html