我们可以编写一段代码,来进行简单的测试:
#include
#include
#include
#include
using namespace leveldb;
int main()
{
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
// 打开一个数据库,不存在就创建
leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());
// 插入一个键值对
status = db->Put(leveldb::WriteOptions(), "hello", "LevelDB");
assert(status.ok());
// 读取键值对
std::string value;
status = db->Get(leveldb::ReadOptions(), "hello", &value);
assert(status.ok());
std::cout << value << std::endl;
delete db;
return 0;
}
编译命令:
g++ test_db.cc -o test_db -L /usr/local/lib64 -lleveldb -lpthread -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++11
指定静态库路径:-L /usr/local/lib64 ,静态库名称:-lleveldb D_GLIBCXX_USE_CXX11_ABI:GCC版本1.5前后接口兼容性问题闭坑参数。
执行test_db文件后,进入/tmp/testdb目录下,看到以下几个文件:
[root@localhost testdb]# cd /tmp/testdb/
[root@localhost testdb]# ll
total 16
-rw-r--r-- 1 root root 34 Oct 14 03:45 000003.log
-rw-r--r-- 1 root root 16 Oct 14 03:45 CURRENT
-rw-r--r-- 1 root root 0 Oct 14 03:45 LOCK
-rw-r--r-- 1 root root 77 Oct 14 03:45 LOG
-rw-r--r-- 1 root root 50 Oct 14 03:45 MANIFEST-000002
[root@localhost testdb]# pwd
/tmp/testdb
[root@localhost testdb]#
喜欢用Java的同学可以引入对应的文件包同样可以完成上面的操作,POM文件:
org.iq80.leveldb
leveldb-api
0.12
org.iq80.leveldb
leveldb
0.12
Java代码:
import org.iq80.leveldb.DB;
import org.iq80.leveldb.DBFactory;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.Iq80DBFactory;
import java.io.File;
import java.io.IOException;
public class TestLevelDB {
public static void main(String[] args) throws IOException {
DBFactory factory = new Iq80DBFactory();
Options options = new Options();
options.createIfMissing(true);
DB db = factory.open(new File("/tmp/testdb"), options);
db.put(Iq80DBFactory.bytes("leveldb") , Iq80DBFactory.bytes("It is leveldb."));
byte[] bytes = db.get(Iq80DBFactory.bytes("leveldb"));
System.out.println(Iq80DBFactory.asString(bytes));
}
}