LevelDB--鍵值對數據庫(KVDB)

特色

  • 鍵值對數據庫,能夠簡單的看作一個只能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
相關文章
相關標籤/搜索