背景

对于一些底层业务系统,同步信息表填充基本信息的操作比较常见,过去的做法多为跨服务同步基础信息表到当前业务表并持久化,需要时join基础表填充字段。这里设计一个简单的CacheService,以内存缓存的方式实现以下功能:

  1. 从外部系统rpc调用刷新缓存并持久化到DB(全量刷新)
  2. 从MQ拿到增量变更数据,刷新缓存并更新DB(增量刷新)
  3. 应用重启从DB拉取全量基础信息维护到内存(初始化)
  4. 无法推MQ的外部系统支持定时任务统一同步(定时刷新)
  5. 需要填充基本字段时直接从内存中可取(读取)

接口

Cacheable,从外部系统接收的数据结构实现转换方法,处理成系统内需要的结构T:

/**
 * @author sunyongfei
 * @date 2022/3/28
 */
public interface Cacheable<T> {

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

    /**
     * 获取缓存值
     * @return
     */
    T getCacheValue();
}

CacheService,单个缓存维护逻辑,可能从不同的数据源同步,统一约束行为

/**
 * @author sunyongfei
 * @genertic T: destination target class
 * @date 2022/3/28
 */
public interface CacheService<T> {

    /**
     * @PostConstruct needed in actual impl bean,
     * if you want to add annotation in the interface, use abstract class instead.
     */
    void initCacheFromDB();

    /**
     * refresh cache
     */
    boolean refreshCache();

    /**
     * refresh single cache item
     */
    boolean refreshCache(T t);

    /**
     * get cache by key
     * @param cacheKey
     * @return
     */
    T getCacheItem(String cacheKey);
}

使用例:

SysInfoSimpleDTO implements XXX, Cacheable<SysInfoDetailDTO>: 接收外部系统的DTO

SysInfoServiceImpl implements XXX, CacheService: 自定义逻辑

SyncServiceImpl: 公共逻辑,如简单的定时任务同步

@Resource
private List<CacheService<?>> cacheServices;

@Scheduled(cron = "0 0/5 * * * ?")
public void refreshCache() {
    if (CollectionUtils.isNotEmpty(cacheServices)) {
        cacheServices.forEach(CacheService::refreshCache);
    }
}

其他逻辑略

标签: java

添加新评论