fxleyu / cu-cafes

This is a repository of Java. And CU is a cafes unders downstairs.
2 stars 0 forks source link

初谈本地缓存 #153

Open fxleyu opened 1 year ago

fxleyu commented 1 year ago
    LoadingCache<String, FrontIndexBanner> cache = CacheBuilder.newBuilder()
            //设置并发级别为1,并发级别是指可以同时写缓存的线程数
            .concurrencyLevel(1)
            //设置缓存容器的初始容量为10
            .initialCapacity(10)
            //设置缓存最大容量为10,超过10之后就会按照LRU最近虽少使用算法来移除缓存项
            .maximumSize(10)
            //设置写缓存后n分钟过期
            .expireAfterWrite(10, TimeUnit.MINUTES)
            //设置缓存的移除通知
            .removalListener(notification -> {
                try {
                    log.info(notification.getKey() + " " + JSON.toJSONString(notification.getValue()) + " remove by " + notification.getCause());
                } catch (Exception exception) {
                    log.error("wtf IndexUserController # cache", exception);
                }
            })
            //build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
            .build(new CacheLoader<String, FrontIndexBanner>() {
                @Override
                public FrontIndexBanner load(String key) {
                    // 没有用户概念,尽量提高性能
                    try {
                        return resourceUserService.indexBanner(NavigationTypeEnum.HOME.getIndex(), new FrontUserContext());
                    } catch (Exception exception) {
                        log.error("wtf IndexUserController # cache load", exception);
                        return new FrontIndexBanner();
                    }
                }
            });

这个缓存好像在高流量下引发「健康检查」失败。

fxleyu commented 1 year ago

健康检查原因是 SQL 线程池挂了导致

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

FrontIndexBanner frontIndexBanner = cache.getIfPresent(CACHE_KEY_4_BANNER);
            if (Objects.isNull(frontIndexBanner)) {
                frontIndexBanner = resourceUserService.indexBanner(NavigationTypeEnum.HOME.getIndex(), new FrontUserContext());
                if (Objects.nonNull(frontIndexBanner)) {
                    cache.put(CACHE_KEY_4_BANNER, frontIndexBanner);
                }
            }
fxleyu commented 1 year ago

WHAT THE FUCK!!!!!!!!!!!