初识LevelDB
认识LevelDB & 源码下载编译
LevelDB是 Google 编写的key-value存储库,提供从Key到Value的有序映射。
LevelDB的代码量相比其他开源项目较少,除了测试之外大约有不到两万行代码。

Mac源码下载和编译运行
LevelDB下载地址:https://github.com/google/leveldb
- 下载与编译
git clone https://github.com/google/leveldb.git
mkdir -p build && cd build
cmake -DCMAKE_BUILD_TYPE=Release .. && cmake --build .
注意:上述命令编译的是Release版本,如果想要Debug,最后一条命令可以改为
cmake -DCMAKE_BUILD_TYPE=Debug .. && cmake --build .
运行报错
CMake Error at CMakeLists.txt:299 (add_subdirectory):
The source directory
/home/xie/cpp/leveldb/third_party/googletest
does not contain a CMakeLists.txt file.
CMake Error at CMakeLists.txt:304 (add_subdirectory):
The source directory
/home/xie/cpp/leveldb/third_party/benchmark
does not contain a CMakeLists.txt file.
......
这是因为third_party下没有googletest和benchmark。
方法一:需要手动把这两个下载下来:
cd third_party
git clone https://github.com/google/benchmark.git
git clone https://github.com/google/googletest.git
方法二:自动下载
git submodule update --init
然后执行cmake命令就可以了。
- 执行测试
首先可以使用leveldb/benchmarks目录下的文件进行测试。

snappy/crc32c/zstd/tcmalloc没有lib
snappy: levelDB中会使用snappy压缩算法来对数据进行压缩,能够在不影响读写性能的情况下减小数据存储空间。压缩速度为 250 MB/秒及以上,无需汇编代码。解压缩时会检测压缩流中是否存在错误。
# snappy的安装和编译
git clone https://github.com/google/snappy.git
cd snappy
git submodule update --init
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ../
make
然后在CMakeLists.txt中修改SNAPPY的配置。找到**check_library_exists(snappy snappy_compress “” HAVE_SNAPPY)**的位置,然后添加以下参数:
link_directories("/Users/julia/CLionProjects/others/snappy/build")
include_directories("/Users/julia/CLionProjects/others/snappy" "/Users/julia/CLionProjects/others/snappy/build")
#注意此行为原来的配置
check_library_exists(snappy snappy_compress "" HAVE_SNAPPY)
#结束
set(HAVE_SNAPPY ON)
然后重新编译LevelDB,运行db_bench得到如下结果:

可以看到snappy是启用的。
其次,我们可以自己写Demo进行测试。在CMakeLists所在目录下创建一个demo进行测试。
//
// Created by Julia on 2024/8/18.
//
#include <cstdio>
#include <iostream>
#include "leveldb/my_comparator.h"
#include "include/leveldb/db.h"
#include "include/leveldb/write_batch.h"
int main() {
// Open a database.
leveldb::DB* db;
leveldb::Options opt;
opt.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(opt, "../db/testdb", &db);
assert(status.ok());

最低0.47元/天 解锁文章
9305

被折叠的 条评论
为什么被折叠?



