1.首先从官网上下载leveldb进行编译
git clone https://github.com/google/leveldb.git cd leveldb make
2.将头文件和动态链接库拷到系统文件里,创建软连接,执行ldconfig命令,将动态链接库加到缓存中,使得系统可以真正使用这个动态链接库
scp -r out-static/lib* out-shared/lib* /usr/local/lib/ cd include/ scp -r leveldb /usr/local/include/ cd leveldb rm -f /usr/local/lib/libleveldb* scp -r out-static/lib* out-shared/lib* /usr/local/lib/ scp -r out-static/lib* out-shared/lib* /usr/local/lib/ ls -l /usr/local/lib/libleveldb* ldconfig
3.写一个样例代码main.cc测试安装好的leveldb
#include "leveldb/db.h" #include <cassert> #include <iostream> using namespace std; using namespace leveldb; int main() { leveldb::DB *db; leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, "testdb", &db); assert(status.ok()); status = db->Put(WriteOptions(), "test", "Hello World!"); assert(status.ok()); string res; status = db->Get(ReadOptions(), "test", &res); assert(status.ok()); cout << res << endl; delete db; return 0; }
4.动态链接库编译如下,动态链接库不需要在当前文件下,系统能自动到相关路径下查找
g++ main.cc -o main -lpthread -lleveldb
注意:一定要加-lpthread,因为leveldb有用到线程相关调用。
5.运行编译好的文件
./main
输出结果:
Hello World!
6.再尝试一下小程序mytest.cc
#include <iostream> #include <cassert> #include <cstdlib> #include <string> #include <leveldb/db.h> using namespace std; int main(void) { leveldb::DB *db; leveldb::Options options; options.create_if_missing=true; leveldb::Status status = leveldb::DB::Open(options,"./testdb",&db); assert(status.ok()); std::string key1="people"; std::string value1="jason"; std::string value; leveldb::Status s=db->Put(leveldb::WriteOptions(),key1,value1); if(s.ok()) s=db->Get(leveldb::ReadOptions(),"people",&value); if(s.ok()) cout<<value<<endl; else cout<<s.ToString()<<endl; delete db; return 0; }
7.编译
g++ mytest.cc -o mytest -lpthread -lleveldb
运行编译好的文件
./mytest
输出结果
jason
8.再加上删除操作呢
#include <iostream> #include <string> #include <assert.h> #include "leveldb/db.h" using namespace std; int main(void) { leveldb::DB *db; leveldb::Options options; options.create_if_missing = true; // open leveldb::Status status = leveldb::DB::Open(options,"/tmp/testdb", &db); assert(status.ok()); string key = "name"; string value = "chenqi"; // write status = db->Put(leveldb::WriteOptions(), key, value); assert(status.ok()); // read status = db->Get(leveldb::ReadOptions(), key, &value); assert(status.ok()); cout<<value<<endl; // delete status = db->Delete(leveldb::WriteOptions(), key); assert(status.ok()); status = db->Get(leveldb::ReadOptions(),key, &value); if(!status.ok()) { cerr<<key<<" "<<status.ToString()<<endl; } else { cout<<key<<"==="<<value<<endl; } // close delete db; return 0; }
9.编译
g++ test.cpp -o test -lpthread -lleveldb
运行
./test
输出结果
chenqi
name NotFound:
10.查看一下testdb里的内容吧
cd /tmp/testdb/
输出结果
000005.ldb 000006.log CURRENT LOCK LOG LOG.old MANIFEST-000004
参考文献:
1.http://luodw.cc/2015/10/14/leveldb-01/
2.https://gist.github.com/dustismo/6203329
3.https://zhuanlan.zhihu.com/p/27329248
4.http://www.cnblogs.com/chenny7/p/4026447.html