C++ 操作 LevelDB

本文详细介绍了LevelDB数据库的安装步骤,包括源码拉取、编译配置及默认安装路径。并通过一个C++示例展示了如何使用LevelDB进行数据库的打开、写入、批量写入和读取等基本操作,最后附上了CMakeLists.txt配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我搭建了个人博客主页, 欢迎访问: blog.joelzho.com

一. 安装 LevelDB

CMake 的版本最低需 >= 3.9

1. 拉取源码

建议下载github-release 下的压缩包, 不建议直接clone代码

git clone --depth=1 https://github.com/google/leveldb.git
cd leveldb

2. 编译 & 安装

mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release .. && cmake --build .
make
sudo make install

默认安装的文件和路径:

/usr/local/lib/libleveldb.a

/usr/local/include/leveldb/c.h
/usr/local/include/leveldb/cache.h
/usr/local/include/leveldb/comparator.h
/usr/local/include/leveldb/db.h
/usr/local/include/leveldb/dumpfile.h
/usr/local/include/leveldb/env.h
/usr/local/include/leveldb/export.h
/usr/local/include/leveldb/filter_policy.h
/usr/local/include/leveldb/iterator.h
/usr/local/include/leveldb/options.h
/usr/local/include/leveldb/slice.h
/usr/local/include/leveldb/status.h
/usr/local/include/leveldb/table_builder.h
/usr/local/include/leveldb/table.h
/usr/local/include/leveldb/write_batch.h
/usr/local/lib/cmake/leveldb/leveldbTargets.cmake
/usr/local/lib/cmake/leveldb/leveldbTargets-release.cmake
/usr/local/lib/cmake/leveldb/leveldbConfig.cmake
/usr/local/lib/cmake/leveldb/leveldbConfigVersion.cmake

二. C++ 操作示例

// Author: Joel<zhoulindeyx@gmail.com>
// Date: 2019-04-12 Fri 14:12
// Desc: Test LevelDB: Open, Put, WriteBatch and Get etc.

#include <leveldb/db.h> // leveldb::*
#include <leveldb/write_batch.h> // leveldb::WriteBatch
#include <string> // string
#include <iostream> // cout, cerr
#include <cassert> // assert

int main()
{
    leveldb::DB *ldbptr = nullptr;
    leveldb::Options options;
    options.create_if_missing = true;
    
    const std::string db_path = "/var/tmp/ldb1.ldb";
    const std::string key = "KEY1";
    const std::string value = "HELLO_LEVELDB";

    leveldb::Status status = leveldb::DB::Open(options, db_path, &ldbptr);
    if(!status.ok()) {
        std::cerr << "open level db error:" << status.ToString() << std::endl;
        return 0;
    }
    assert(ldbptr != nullptr);
    std::cout << "open level db successfully !" << std::endl;

    // put insert
    {
        leveldb::WriteOptions putOptions;
        putOptions.sync = true;
        // const leveldb::Slice s_key = leveldb::Slice(key);
        // const leveldb::Slice s_value = leveldb::Slice(key);
        status = ldbptr->Put(putOptions, key, value);
        if (!status.ok()) {
            std::cerr << "put data error:" << status.ToString() << std::endl;
            return 0;
        }
        std::cout << "put data successfully!" << std::endl;
    }

    // test batch write
    {
        leveldb::WriteBatch writeBatch;
        writeBatch.Put("username", "Joel");
        writeBatch.Put("gender", "Male");
        writeBatch.Put("job", "Programmer");

        status = ldbptr->Write(leveldb::WriteOptions(), &writeBatch);
        if (!status.ok()) {
            std::cerr << "batch write data error:" << status.ToString() << std::endl;
            return 0;
        }
        std::cout << "batch write data successfully!" << std::endl;
    }

    // get test
    {
        leveldb::ReadOptions getOptions;
        std::string rdVal;
        // Slice(const std::string& s)
        status = ldbptr->Get(getOptions, key, &rdVal);
        if (!status.ok()) {
            std::cerr << "get data error:" << status.ToString() << std::endl;
            return 0;
        }
        std::cout << "get data successfully:" << rdVal << std::endl;
        assert(value == rdVal);
    }

    // test iterator
    {
        leveldb::Iterator *iterator = ldbptr->NewIterator(leveldb::ReadOptions());
        if(!iterator) {
            std::cerr << "can not new iterator" << std::endl;
            return 0;
        }

        // caller must call one of the Seek methods on the iterator before using it
        iterator->SeekToFirst();
        std::cout << "=========== iterator begin ===========" << std::endl;
        while(iterator->Valid())
        {
            leveldb::Slice sKey = iterator->key();
            leveldb::Slice sVal = iterator->value();
            std::cout << "key:" << sKey.ToString() << "\tvalue:" << sVal.ToString() << std::endl;
            iterator->Next();
        }
        std::cout << "=========== iterator end ===========" << std::endl;

        // caller should delete the iterator when it is no longer needed
        delete(iterator);
    }

    // caller should delete leveldb::DB ptr when it is no longer needed
    delete(ldbptr);

    std::cout << "test completed !" << std::endl;
    return 0;
}

三. 示例源码 CMakeLists.txt

cmake_minimum_required(VERSION 3.13)
project(LevelDBTest)

set(CMAKE_CXX_STANDARD 11)

add_executable(LevelDBTest main.cpp)
target_link_libraries(LevelDBTest leveldb.a)
target_link_libraries(LevelDBTest pthread -lm -ldl)

四. 注意:

要正常编包含LevelDB 的项目需要链接 pthread,
就像我的示例代码的 CMakeLists.txt 最后一行写的那样.

五. 参考资料

LevelDB 官网: http://leveldb.org/
LevelDB 源码: https://github.com/google/leveldb
LevelDB 操作文档: https://github.com/google/leveldb/blob/master/doc/index.md
CMake 官网: https://cmake.org/

leveldb实现解析 淘宝-核心系统研发-存储 那岩 neveray@gmail.com 2011-12-13 目录 一、 代码目录结构 ....................................................................... 1 1. doc/ ............................................................................ 1 2. include/leveldb/ ................................................................. 1 3. db/ ............................................................................. 1 4. table/........................................................................... 1 5. port/ ........................................................................... 1 6. util/ ........................................................................... 1 7. helper/memenv/ ................................................................... 1 二、 基本概念 .......................................................................... 1 1. Slice (include/leveldb/slice.h) .................................................. 1 2. Option (include/leveldb/option.h) .............................................. 2 3. Env (include/leveldb/env.h util/env_posix.h) .................................... 3 4. varint (util/coding.h) ........................................................... 3 5. ValueType (db/dbformat.h) ...................................................... 3 6. SequnceNnumber (db/dbformat.h) ................................................. 4 7. user key......................................................................... 4 8. ParsedInternalKey (db/dbformat.h) .............................................. 4 9. InternalKey (db/dbformat.h) ...................................................... 4 10. LookupKey (db/dbformat.h) ........................................................ 4 11. Comparator (include/leveldb/comparator.h util/comparator.cc) .................... 4 12. InternalKeyComparator (db/dbformat.h) ............................................ 5 13. WriteBatch (db/write_batch.cc) ................................................. 5 14. Memtable (db/memtable.cc db/skiplist.h) .......................................... 5 15. Sstable (table/table.cc) ......................................................... 5 16. FileMetaData (db/version_edit.h) ............................................... 5 17. block (table/block.cc) ........................................................... 6 18. BlockHandle(table/format.h) ...................................................... 6 19. FileNumber(db/dbformat.h) ...................................................... 6 20. filename (db/filename.cc) ........................................................ 6 21. level-n (db/version_set.h) ....................................................... 7 22. Compact (db/db_impl.cc db/version_set.cc) ........................................ 7 23. Compaction(db/version_set.cc) .................................................... 7 24. Version (db/version_set.cc) ...................................................... 8 25. VersionSet (db/version_set.cc) ................................................. 9 26. VersionEdit(db/version_edit.cc) ................................................. 10 27. VersionSet::Builder (db/version_set.cc) ......................................... 11 28. Manifest(descriptor)(db/version_set.cc)...................................... 12 29. TableBuilder/BlockBuilder(table/table_builder.cc table/block_builder.cc) ......... 12 30. Iterator (include/leveldb/iterator.h) ........................................... 12 三、 存储结构的格式定义与操作 .......................................................... 12 1. memtable (db/skiplist.h db/memtable) ............................................ 12 2. block of sstable (table/block_builder.cc table/block.cc) ......................... 14 3. sstable (table/table_bulder.cc/table.cc) ........................................ 16 4. block of log (db/log_format.h db/log_writer.cc db/log_reader.cc) .............. 18 5. log (db/log_format.h db/log_writer.cc db/log_reader.cc) ........................ 18 6. cache(util/cache.cc) .......................................................... 19 7. Snapshot (include/leveldb/snapshot.h) ......................................... 19 8. Iterator (include/leveldb/iterator.h) ........................................... 19 四、 主要流程 ......................................................................... 24 1. open ........................................................................... 24 2. put ............................................................................ 25 3. get ............................................................................ 25 4. delete.......................................................................... 26 5. snapshot........................................................................ 26 6. NewIterator ..................................................................... 26 7. compact......................................................................... 26 五、 总结 ............................................................................. 30 1. 设计/实现中的优化 ............................................................... 30 2. 可以做的优化 .................................................................... 31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值