特点
键值对数据库,可以简单的看做一个只能get/put的map
写入速度比查询速度更快
demo
考虑到我们使用的时候多半会用到字符串,所以我进行了一点画蛇添足的扩展
gitee地址
https://gitee.com/ichiva/leveldb-demo.git
主要依赖
org.iq80.leveldb
leveldb
0.7
org.iq80.leveldb
leveldb-api
0.7
编写测试用例
连接数据库
DB db = null;
@Before
public void Before() throws IOException {
DBFactory factory = new Iq80DBFactory();
Options options = new Options();
db = factory.open(new File("./leveldb"), options);
}
写入数据
@Test
public void put(){
db.put("二哥".getBytes(),"关羽".getBytes());
}
获取数据
@Test
public void get(){
byte[] bytes = db.get("二哥".getBytes());
System.out.println("二哥 => " + new String(bytes));
}
遍历数据库
@Test
public void iterator(){
DBIterator it = db.iterator();
while (it.hasNext()) {
Map.Entry next = it.next();
System.out.println("key = " + new String(next.getKey()));
System.out.println("val = " + new String(next.getValue()));
}
}
别忘了关闭数据库
@After
public void After() throws IOException {
if(null != db) db.close();
}
画蛇添足的来扩展一下,用于简化字符串操作
/**
* 简化字符串操作
*/
public class StringDB extends DbImpl {
public static final String CHAR_SET = "UTF-8";
public StringDB(Options options, File databaseDir) throws IOException {
super(options, databaseDir);
}
public StringDB(String dir) throws IOException {
this(new Options(),new File(dir));
}
public void put(String key, String value) throws DBException {
try {
put(key.getBytes(CHAR_SET),value.getBytes(CHAR_SET));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public String get(String key) throws DBException {
try {
return new String(get(key.getBytes(CHAR_SET)),CHAR_SET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
总结,leveldb用起来就像是一个硬盘版的redis,唯一不足的是没有提供key的过滤功能
PS.这货是谷歌的亲儿子,应该可以放心的在生成环境中使用
gitee地址
https://gitee.com/ichiva/leveldb-demo.git