leveldb简单使用例子

1.下载代码
git clone https://github.com/google/leveldb.git

2.编译代码,之后会生成libleveldb.a文件
由于level把本来需要依赖的库都自己实现了,所以直接make就行,不过在g++3版本下不能会出错,需要在makefile中修改CXXFLAGS参数
CXXFLAGS += -fno-access-control -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT)


3.写测试代码

#include <cassert>
#include <iostream>
#include "leveldb/db.h"

int main() {
    leveldb::DB *db;
    leveldb::Options options;
    options.create_if_missing = true;
    leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
    assert(status.ok());

    std::cout << "leveldb open success!" << std::endl;

    std::string value;
    std::string key1 = "testkey1";
    leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value);
    if (s.IsNotFound()) {
        std::cout << "can not found for key:" << key1 << std::endl;
        db->Put(leveldb::WriteOptions(), key1, "testvalue1");
    }

    s = db->Get(leveldb::ReadOptions(), key1, &value);
    if (s.ok()) {
        std::cout << "found key:" << key1 << ",value:" << value << std::endl;
    }
    s = db->Delete(leveldb::WriteOptions(), key1);
    if (s.ok()) {
        std::cout << "delete key success which key:" << key1 << std::endl;
    }
    s = db->Get(leveldb::ReadOptions(), key1, &value);
    if (s.IsNotFound()) {
        std::cout << "can not found after delete for key:" << key1 << std::endl;
    }

    delete db;
	return 0;
}


4.编译 && 运行
g++ -I src -I /home/liao/github/leveldb/include src/leveldb_test.cpp /home/liao/github/leveldb/libleveldb.a -lpthread -o leveldb_test
./leveldb_test


一些感想: 粗略看了下代码,leveldb逻辑上相对清晰,代码耦合度低,可扩展性强,同时把一些常用的库都自己实现了,比如log库,test库,这样减少了使用者的成本,但是test代码和src的代码放在一起了,感觉有点乱,之后继续学习吧

猜你喜欢

转载自finallygo.iteye.com/blog/2184207