序
本文主要研究一下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())
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。