leveldb 安装及使用

leveldb 简介

leveldb 是 Google 用 C++ 开发的一个快速的键值对存储数据库,提供从字符串键到字符串值的有序映射。

leveldb 安装

下载 leveldb

git clone https://github.com/google/leveldb.git

编译 leveldb

cd leveldb/
make

编译的动态库和静态库分别在 out-sharedout-static 下:

ls leveldb/out-shared/libleveldb.so.1.20
ls leveldb/out-static/libleveldb.a

安装 leveldb

只有动态库需要安装,静态库在你编译的时候直接链接即可

# cp leveldb header file
sudo cp -r /leveldb/include/ /usr/include/

# cp lib to /usr/lib/
sudo cp /leveldb/out-shared/libleveldb.so.1.20 /usr/lib/

# create link
sudo ln -s /usr/lib/libleveldb.so.1.20 /usr/lib/libleveldb.so.1
sudo ln -s /usr/lib/libleveldb.so.1.20 /usr/lib/libleveldb.so

# update lib cache
sudo ldconfig

查看安装是否成功

ls /usr/lib/libleveldb.so*
# 显示下面 3 个文件即安装成功
/usr/lib/libleveldb.so.1.20
/usr/lib/libleveldb.so.1
/usr/lib/libleveldb.so

leveldb 使用

我们来编写一个 hello_leveldb.cc 来测试我们的 leveldb

#include <iostream>
#include <cassert>
#include <cstdlib>
#include <string>
// 包含必要的头文件
#include <leveldb/db.h>

using namespace std;

int main(void)
{
    leveldb::DB *db = nullptr;
    leveldb::Options options;

    // 如果数据库不存在就创建
    options.create_if_missing = true;

    // 创建的数据库在 /tmp/testdb
    leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
    assert(status.ok());

    std::string key = "A";
    std::string value = "a";
    std::string get_value;

    // 写入 key1 -> value1
    leveldb::Status s = db->Put(leveldb::WriteOptions(), key, value);

    // 写入成功,就读取 key:people 对应的 value
    if (s.ok())
        s = db->Get(leveldb::ReadOptions(), "A", &get_value);

    // 读取成功就输出
    if (s.ok())
        cout << get_value << endl;
    else
        cout << s.ToString() << endl;

    delete db;

    return 0;
}

编译 - 静态链接

cp leveldb/out-static/libleveldb.a ./
g++ hello_leveldb.cc -o hello_leveldb ./libleveldb.a -lpthread

编译 - 动态链接

g++ hello_leveldb.cc -o hello_leveldb -lpthread -lleveldb

运行结果

./hello_leveldb
# 输出值为 a,说明成功存储和获取
a

# 查看数据库
ls /tmp/testdb


作者:cdeveloper
链接:http://www.jianshu.com/p/8392acf7c9db
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自hugoren.iteye.com/blog/2393073