packagecom.dearcloud.utils.leveldb;importlombok.extern.log4j.Log4j2;importorg.fusesource.leveldbjni.JniDBFactory;importorg.iq80.leveldb.DB;importorg.iq80.leveldb.Options;importjava.io.File;importjava.io.IOException;importjava.util.Map;importjava.util.Objects;importjava.util.concurrent.ConcurrentLinkedQueue;
@Log4j2public classLeveldbUtils {privateDB db;privateFile file;privateOptions options;publicLeveldbUtils(File file, Integer cahceSize, Integer blockSize) {
Objects.requireNonNull(file);
File[] files=file.listFiles();if (files != null && files.length > 0) {
log.warn("levelDb directory is not empty. file=[{}]", file);
}this.file =file;if (blockSize == null) blockSize = 1024 * 1024 * 10;if (cahceSize == null) cahceSize = 1024 * 1024 * 20;
options= newOptions();
options.cacheSize(cahceSize);
options.blockSize(blockSize);
options.maxOpenFiles(5);
options.writeBufferSize(10000000);//单个文件32MB
reOpenDb();
}private voidopenDb() {synchronized (this) {boolean isok = false;try{
JniDBFactory.factory.destroy(file, options);
isok= true;
}catch(Exception ex) {
log.warn("levelDb destroy failed. file=[{}]", file);
}try{
db=JniDBFactory.factory.open(file, options);
isok= isok && true;
}catch(IOException e) {
log.error("levelDb rebuild init failed. file=[{}]", file);
}if(isok)
log.info("leveldb rebuild success.");
}
}public synchronized void put(String key, byte[] value) {try{
db.put(JniDBFactory.bytes(key), value);
}catch(Exception ex) {
log.warn("[save to localDb] save single item to localDb failed.", ex);
}
}public synchronized void put(ConcurrentLinkedQueue>data) {for (Map.Entrydatum : data) {try{
db.put(datum.getKey(), datum.getValue());
}catch(Exception ex) {
log.warn("[save to localDb] save to localDb failed.", ex);
}
}
}public synchronized voidclose() {try{
db.close();
JniDBFactory.factory.destroy(file, options);
}catch(IOException e) {
log.error("[LeveldbUtils]:levelDb close failed.", e);
}
}
}