定时刷新本地缓存

说明

使用guava cache作为本地缓存组件,并通过Spring中SchedulingConfigurer定时刷新本地缓存

代码

(1)

/**
 * @Author Caocs
 * @Date 2023/2/16
 */
public interface ILocalCache<V> {

    /**
     * @return 获取缓存(如果缓存中不存在则重新加载)
     */
    V getLocalCache();

    /**
     * @return 缓存key
     */
    String getCacheKey();

    /**
     * 刷新缓存
     */
    void refreshCache();

    /**
     * @return 是否需要定时刷新(SchedulingConfigurer时用到)
     */
    boolean needTimedRefreshCache();

    /**
     * cron表达式(SchedulingConfigurer时用到)
     * 默认:每天凌晨2点执行一次("0 0 2 * * ?")
     */
    default String getCronExpr() {
        return "0 0 2 * * ?";
    }
}

(2)

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
/**
 * @Author Caocs
 * @Date 2023/2/16
 */
public abstract class AbstractLocalCache<V> implements ILocalCache<V> {

    private final Cache<String, V> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(48, TimeUnit.HOURS).build();

    /**
     * @return 加载缓存数据, 确保不会返回空集, 用null代替
     */
    protected abstract V loadCache();

    /**
     * @param cacheData 待cache的数据
     * @return 验证cacheData是否有效
     */
    protected abstract boolean isValidCache(V cacheData);

    /**
     * @return 获取缓存数据, 如果缓存中没有, 会执行load()加载
     */
    @Override
    public V getLocalCache() {
        V value = null;
        try {
            value = (V) cache.get(getCacheKey(), this::loadCache);
        } catch (Exception ex) {
            CLogHelper.error("", ex.getMessage());
        }
        return value;
    }

    /**
     * 刷新缓存
     */
    @Override
    public void refreshCache() {
        synchronized (this) {
            long start = System.currentTimeMillis();
            V value = loadCache();
            if (isValidCache(value)) {
                cache.put(getCacheKey(), value);
            }
            CLogHelper.info(getCacheKey(), String.format("cost %s ms", System.currentTimeMillis() - start));
        }
    }

}

(3)通过SchedulingConfigurer 定时刷新本地缓存。

import com.ctrip.framework.clogging.common.util.StringUtil;
import com.google.common.annotations.VisibleForTesting;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Author Caocs
 * @Date 2023/2/16
 * 本地缓存初始化、加载、定时刷新。
 * 刷新方式:
 * (1)使用SchedulingConfigurer,定时刷新
 * (2)监听QConfig配置文件中cacheKey版本变更,刷新本地缓存。
 * (3)监听QMQ消息中cacheKey,刷新本地缓存。
 */
@EnableScheduling
@Component
public class LocalCacheManager<V> implements SchedulingConfigurer {

    private final List<ILocalCache<V>> localCaches;

    public LocalCacheManager(List<ILocalCache<V>> localCaches) {
        this.localCaches = localCaches;
    }

    /**
     * 初始加载缓存数据
     */
    @PostConstruct
    @VisibleForTesting
    void initCache() {
        localCaches.forEach(item -> {
            if (StringUtil.isNotEmpty(item.getCacheKey())) {
                item.getLocalCache();
            }
        });
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        localCaches.forEach(item -> {
            if (item.needTimedRefreshCache()) {
                taskRegistrar.addTriggerTask(
                        () -> {
                            item.refreshCache();
                        },
                        triggerContext -> new CronTrigger(item.getCronExpr()).nextExecutionTime(triggerContext)
                );
            }
        });
    }
}

(4)模拟数据缓存

import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Caocs
 * @Date 2023/2/16
 */
@Component
public class CityCache extends AbstractLocalCache<Map<String, String>> {

	// 模拟调用接口获取数据
    @Override
    protected Map<String, String> loadCache() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, String> cacheData = new HashMap<>();
        cacheData.put("bj", "beijing");
        return cacheData;
    }

    @Override
    protected boolean isValidCache(Map<String, String> cacheData) {
        return MapUtils.isNotEmpty(cacheData);
    }

    @Override
    public String getCacheKey() {
        return "local_cache_city";
    }

    @Override
    public boolean needTimedRefreshCache() {
        return true;
    }
}

(5)测试缓存刷新

import com.ctrip.flight.backendservice.backofficetool.ibuivr.local.CityCache;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
/**
 * @Author Caocs
 * @Date 2022/11/9
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = IbuAppStarter.class)
public class SpringBootBeanTest {
    
    @Autowired
    CityCache cityCache;

    @Test
    public void testLocalCache() {
        Map<String, String> cityMap = cityCache.getLocalCache();
        try {
            Thread.sleep(1000 * 60 * 10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(缓存,java,spring)