前言
LevelDB 是一種Key-Value存儲數(shù)據(jù)庫
性能非常強悍 百度百科上介紹 可以支撐十億級
這段時間在研究區(qū)塊鏈的時候發(fā)現(xiàn)的這個數(shù)據(jù)庫
引入SDK
<dependency>
<groupId>org.iq80.leveldb</groupId>
<artifactId>leveldb-api</artifactId>
<version>0.10</version>
</dependency>
<dependency>
<groupId>org.iq80.leveldb</groupId>
<artifactId>leveldb</artifactId>
<version>0.10</version>
</dependency>
初始化DB
DBFactory factory = new Iq80DBFactory();
Options options = new Options();
options.createIfMissing(true);
//folder 是db存儲目錄
DB db = factory.open(new File(folder), options);
存儲Key Value 值
//levelDB 的api存儲都是字節(jié)數(shù)組 所以這里需要轉(zhuǎn)成字節(jié)數(shù)組
db.put(Iq80DBFactory.bytes(key), Iq80DBFactory.bytes(value));
獲取Value
byte[] bytes = db.get(Iq80DBFactory.bytes(key));
String value = Iq80DBFactory.asString(bytes);
刪除|更改
//刪除
db.delete(Iq80DBFactory.bytes(key));
//更改 重新put新的key - value即可
db.put(Iq80DBFactory.bytes(key), Iq80DBFactory.bytes(value));
遍歷所有數(shù)據(jù)
public LinkedHashMap<String, String> iteratorDb() {
DBIterator iterator = db.iterator();
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
while (iterator.hasNext()) {
Map.Entry<byte[], byte[]> next = iterator.next();
String key = Iq80DBFactory.asString(next.getKey());
String value = Iq80DBFactory.asString(next.getValue());
linkedHashMap.put(key, value);
}
return linkedHashMap;
}
測試插入一百萬條數(shù)據(jù)
基于SpringBoot搭建的控制器
隨機生成 指定數(shù)量的UUID 并且插入到LevelDB
從請求 到響應 5.5秒左右 如果再拋掉生成UUID的時間 可能更快 哈哈
@ResponseBody
@GetMapping("/generate")
public ResponeEntity generate(Long count) {
DB db = levelDb.getDb();
//創(chuàng)建批量處理
WriteBatch batch = db.createWriteBatch();
for (int i = 0; i < count; i++) {
String uuid = UUID.randomUUID().toString();
batch.put(Iq80DBFactory.bytes(uuid), Iq80DBFactory.bytes(uuid));
}
//執(zhí)行寫入
db.write(batch);
return buildRespone(null);
}
測試從一百萬數(shù)據(jù)中取出一條
PostMan 請求到響應時間 19毫秒
@ResponseBody
@GetMapping("/getLevel")
public ResponeEntity getLevel(String key) {
byte[] bytes = db.get(Iq80DBFactory.bytes(key));
String value = Iq80DBFactory.asString(bytes);
return buildRespone(value);
}