5

LoadingCache简单实例,使用google缓存机制缓存每天数据库第一条数据并保存

 2 years ago
source link: https://segmentfault.com/a/1190000041361004
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

LoadingCache简单实例,使用google缓存机制缓存每天数据库第一条数据并保存

发布于 今天 02:33

使用LoadingCache缓存每天数据库第一条数据并保存

 private LoadingCache<String, Integer> minId = CacheBuilder.newBuilder().expireAfterWrite(1L, TimeUnit.DAYS).build(new CacheLoader<String, Integer>() {
    @Override
    public Integer load(String mixdate) throws Exception {
      Date date = LocalDate.parse(StringUtils.substringAfter(s, "@")).toDate();
      // 在本地没有缓存的时候会调用该方法进行加载,将获取的值进行缓存并返回结果
      if (ACTIVE_COUNTER.startsWith(mixdate)) {
        LoginLog loginLog = loginLogRepository.getTopByLoginTimeBeforeOrderByIdDesc(date);
        if (loginLog != null) {
          return loginLog.getId();
        }
      } else if (PLAYED_COUNTER.startsWith(mixdate)) {
        ViewHistory viewHistory = viewHistoryRepository.getTopByViewtimeBeforeOrderByIdDesc(date);
        if (viewHistory != null) {
          return viewHistory.getId();
        }
      } else if (ADCLICK_COUNTER.startsWith(mixdate)) {
        AdvClickHistory advClickHistory = advClickHistoryRepository.getTopByCreateTimeBeforeOrderByIdDesc(date);
        if (advClickHistory != null) {
          return advClickHistory.getId();
        }
      }
      return 0;
    }
  });
minId.getUnchecked(StringUtils.join(type, "@", date));

在这里取出当天的数据key,因为每天date都不一样,所以会获取当天的第一条数据,并缓存起来!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK