本文主要研究一下claudb的DatabaseCleaner

DatabaseCleaner

claudb-1.7.1/src/main/java/com/github/tonivade/claudb/data/DatabaseCleaner.java

public class DatabaseCleaner {

  private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseCleaner.class);

  private final DBServerContext server;
  private final DBConfig config;

  private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

  public DatabaseCleaner(DBServerContext server, DBConfig config) {
    this.server = server;
    this.config = config;
  }

  public void start() {
    executor.scheduleWithFixedDelay(this::clean,
        config.getCleanPeriod(), config.getCleanPeriod(), TimeUnit.SECONDS);
  }

  public void stop() {
    executor.shutdown();
  }

  private void clean() {
    LOGGER.debug("cleaning database: running");
    server.clean(Instant.now());
    LOGGER.debug("cleaning database: done");
  }
}
  • DatabaseCleaner的start方法每隔config.getCleanPeriod()(默认30)秒调度执行clean方法;clear方法执行server.clean(Instant.now())

clean

claudb-1.7.1/src/main/java/com/github/tonivade/claudb/ClauDB.java

public class ClauDB extends RespServerContext implements DBServerContext {

    //......

  public void clean(Instant now) {
    executeOn(Observable.create(observable -> {
      getState().evictExpired(now);
      observable.onComplete();
    })).blockingSubscribe();
  }

    //......

}
  • ClauDB的clean方法执行getState().evictExpired(now)

evictExpired

claudb-1.7.1/src/main/java/com/github/tonivade/claudb/DBServerState.java

public class DBServerState {

    //......

  public void evictExpired(Instant now) {
    for (Database database : databases) {
      database.evictableKeys(now).forEach(database::remove);
    }
  }

    //......

}
  • evictExpired方法执行database.evictableKeys(now).forEach(database::remove)

evictableKeys

claudb-1.7.1/src/main/java/com/github/tonivade/claudb/data/Database.java

public interface Database {

  //......

  default ImmutableSet<DatabaseKey> evictableKeys(Instant now) {
    return entrySet()
        .filter(entry -> entry.get2().isExpired(now))
        .map(Tuple2::get1);
  }

  //......

}
  • evictableKeys方法遍历entrySet,找出DatabaseValue的isExpired为true的ImmutableSet

小结

DatabaseCleaner的start方法每隔config.getCleanPeriod()(默认30)秒调度执行clean方法;clear方法执行server.clean(Instant.now())

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...