关于redis:聊聊claudb的DatabaseCleaner

32次阅读

共计 1996 个字符,预计需要花费 5 分钟才能阅读完成。

本文次要钻研一下 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

  • DatabaseCleaner

正文完
 0