C++引入leveldb
编译安装:
git clone --recurse-submodules https://github.com/google/leveldb.git
cd leveldb
mkdir -p build && cd build
cmake -DCMAKE_BUILD_TYPE=Release .. && cmake --build .
sudo make install
C++工程引入leveldb库,需链接-lleveldb -lpthread
leveldb使用示例
#include <iostream>
#include <leveldb/db.h>
int main(int argc, char const *argv[])
{
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, "testdb", &db);
if (!status.ok()) {
std::cout << "open db failed" << std::endl;
return -1;
}
std::cout << "open db success" << std::endl;
status = db->Put(leveldb::WriteOptions(), "rc", "Hello rc!");
if (!status.ok()) {
std::cout << "put db failed" << std::endl;
return -1;
}
std::cout << "put db success" << std::endl;
std::string res;
status = db->Get(leveldb::ReadOptions(), "rc", &res);
if (!status.ok()) {
std::cout << "get db failed" << std::endl;
return -1;
}
std::cout << "get db success" << std::endl;
std::cout << "get " << res << std::endl;
delete db;
return 0;
}
options选项含义
struct options {
// 比较器,用来决定key在表中的排列顺序
// 默认的比较器,按字典序排序
const Comparator* comparator;
// 为true表示,数据库不存在则创建
bool create_if_missing = false;
// 为true表示,数据库存在则报错
bool error_if_exists = false;
// 为true表示,严格检错模式,可能导致数据库不可用
bool paranoid_checks = false;
// 平台兼容性相关,暂不了解
// 默认为Env::Default()
Env* env;
// 为null则日志信息和数据内容写在同一个文件
// 不为null,单独写到info_log文件
Logger* info_log = nullptr;
// 大的写缓存可以提升性能,特别是大块数据加载的时候
// 但是会导致下次打开数据库花更多时间来recovery
size_t write_buffer_size = 4 * 1024 * 1024;
// 数据库最多能打开的文件数
// 一般每2MB的working set会用一个文件
int max_open_files = 1000;
// 块缓存,块就是从磁盘读取的一个单位
// 为null,用8MB的内部缓存
// 不为null,则用指定的缓存
Cache* block_cache = nullptr;
// 块的大小
size_t block_size = 4 * 1024;
// 差分编码时key的数目,可以动态改变,建议不修改。
int block_restart_interval = 16;
// leveldb最大写文件的大小,达到该值将创建新的文件
// 一般不用更改
size_t max_file_size = 2 * 1024 * 1024;
// 压缩算法,可以算kSnappyCompression和KNoCompression
// kSnappyCompression一般压缩速率:
// ~200-500MB/s compression
// ~400-800MB/s decompression
CompressionType compression = kSnappyCompression;
// 为true的话,会采用追加模式写manifest和log,可以提升数据库开启速度
bool reuse_logs = false;
// 如果用NewBloomFilterPolicy可以提升读取速度
const FilterPolicy* filter_policy = nullptr;
};
struct ReadOptions {
// 为true,则读取数据的时候会检测校验和
bool verify_checksums = false;
// 是否将此次读数据的迭代缓存到内存
// 设置为false,可以提升大块数据扫描效率
bool fill_cache = true;
// 不为null,则从指定快照中读取数据
// 为null,则从当前开始读取时的快照中读取数据
const Snapshot* snapshot = nullptr;
};
struct WriteOptions {
// 是否同步写,为true会降低写速率
bool sync = false;
};
status错误代码
class Status {
public:
// 运行成功
bool ok() const;
// 未找到错误
bool IsNotFound() const;
// 崩溃错误
bool IsCorruption() const
// IO错误
bool IsIOError() const;
// 不支持错误
bool IsNotSupportedError() const;
// 参数非法错误
bool IsInvalidArgument() const;
};