特色
- 键值对数据库,能够简单的看作一个只能get/put的map
- 写入速度比查询速度更快
demo
考虑到咱们使用的时候多半会用到字符串,因此我进行了一点多此一举的扩展git
gitee地址
https://gitee.com/ichiva/leveldb-demo.git
主要依赖
<dependency> <groupId>org.iq80.leveldb</groupId> <artifactId>leveldb</artifactId> <version>0.7</version> </dependency> <dependency> <groupId>org.iq80.leveldb</groupId> <artifactId>leveldb-api</artifactId> <version>0.7</version> </dependency>
编写测试用例
链接数据库
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<byte[], byte[]> 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的过滤功能redis
PS.这货是谷歌的亲儿子,应该能够放心的在生成环境中使用数据库
gitee地址
https://gitee.com/ichiva/leveldb-demo.git