leveldb的介绍和安装

leveldb

Posted by bbkgl on November 23, 2019

不向人间怨不平

相期浴火凤凰生

leveldb是谷歌开发的快速的KV数据库引擎,由Google传奇工程师Jeff Dean和Sanjay Ghemawat开发并开源。leveldb整体的设计比较巧妙,代码质量也有非常多的值得借鉴的地方,所以我打算阅读leveldb的源码,然后再自己撸一个KV数据库。

leveldb下载

现在的leveldb已经支持cmake了,所以可以先安装cmake,cmake版本要求>=3.9。安装完cmake以后直接clone:

git clone https://github.com/google/leveldb.git  # https
git cline git@github.com:google/leveldb.git # ssh

我看了下最新的commit是支持了googletest,但是发现他只是在cmake里面加了googletest,并没有在项目里加入第三方库,所以cmake怎么都报错:

CMake Error at CMakeLists.txt:302 (add_subdirectory):
  add_subdirectory given source "third_party/googletest" which is not an
  existing directory.
CMake Error at CMakeLists.txt:306 (set_property):
  set_property could not find TARGET gtest.  Perhaps it has not yet been
  created.
CMake Error at CMakeLists.txt:308 (set_property):
  set_property could not find TARGET gmock.  Perhaps it has not yet been
  created.

大概是这样,然后我就找到了他最开始加入cmake的commit,所以切换到那次commit:

git checkout 739c25100e46576cdcdfff2d6f43f9f7008103c7

然后就编译和生成可执行文件:

mkdir build && cd build
cmake ..
make

等编译完成就好了,leveldb没有依赖任何第三方库,在linux下应该是能顺利编译过的。

测试运行

在项目根目录新建一个目录作为测试目录,然后创建第一个测试文件:

mkdir test
touch test1.cc

然后在文件里写下代码:

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

int main() {
    leveldb::DB *db;
    leveldb::Options options;
    options.create_if_missing = true;
    // 打开一个leveldb数据库
    leveldb::Status status = leveldb::DB::Open(options, "testdb", &db);
    assert(status.ok());

    status = db->Put(leveldb::WriteOptions(), "bbkgl", "https://bbkgl.github.io");
    assert(status.ok());
    std::string res;
    status = db->Get(leveldb::ReadOptions(), "bbkgl", &res);
    assert(status.ok());
    std::cout << res << std::endl;

    delete db;
    return 0;
}

当然要让这个文件能生成可执行文件,还得修改CMakeLists.txt:

if(NOT BUILD_SHARED_LIBS)
    leveldb_test("${PROJECT_SOURCE_DIR}/test/test1.cc")   # 加入这句
    leveldb_test("${PROJECT_SOURCE_DIR}/db/autocompact_test.cc")
    leveldb_test("${PROJECT_SOURCE_DIR}/db/corruption_test.cc")

然后在build文件夹下:

cmake ..
make
./test1

就能看到输出: