LevelDB project 1 10225501460 林子骥 10211900416 郭夏辉
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 

135 行
3.0 KiB

#include "leveldb/db.h"
#include "leveldb/filter_policy.h"
#include "leveldb/env.h"
#include "leveldb/db.h"
using namespace leveldb;
constexpr int value_size = 2048;
constexpr int data_size = 128 << 20;
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace leveldb;
// 3. 数据管理(Manifest/创建/恢复数据库)
Status OpenDB(std::string dbName, DB **db) {
Options options;
options.create_if_missing = true;
options.filter_policy = NewBloomFilterPolicy(10);
return DB::Open(options, dbName, db);
}
// 1. 存储(数据结构与写入)
// 4. 数据合并(Compaction)
//void InsertData(DB *db) {
// WriteOptions writeOptions;
// int key_num = data_size / value_size;
// srand(static_cast<unsigned int>(time(0)));
//
// for (int i = 0; i < key_num; i++) {
// int key_ = rand() % key_num+1;
// std::string key = std::to_string(key_);
// std::string value(value_size, 'a');
// db->Put(writeOptions, key, value);
// }
//}
void InsertData(DB *db, uint64_t ttl/* second */) {
WriteOptions writeOptions;
int key_num = data_size / value_size;
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < key_num; i++) {
int key_ = rand() % key_num+1;
key_ = 1;
std::string key = std::to_string(key_);
std::string value(value_size, 'a');
db->Put(writeOptions, key, value, ttl);
std::cout << "time to alive" << ttl << std::endl;
break;
}
}
// 2. 数据访问(如何读数据)
void GetData(DB *db, int size = (1 << 30)) {
ReadOptions readOptions;
int key_num = data_size / value_size;
// 点查
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < 100; i++) {
int key_ = rand() % key_num+1;
std::string key = std::to_string(key_);
std::string value;
db->Get(readOptions, key, &value);
//break;
}
// 范围查询
Iterator *iter = db->NewIterator(readOptions);
iter->SeekToFirst();
while (iter->Valid()) {
iter->Next();
}
delete iter;
}
int main() {
// DB *db;
// if(OpenDB("testdb", &db).ok()) {
// uint64_t ttl = 20;
//
// InsertData(db, ttl);
// delete db;
// }
//
// if(OpenDB("testdb", &db).ok()) {
// GetData(db);
// delete db;
// }
//
DB *db;
if(OpenDB("testdb", &db).ok() == false) {
std::cerr << "open db failed" << std::endl;
abort();
}
uint64_t ttl = 200;
InsertData(db, ttl);
ReadOptions readOptions;
Status status;
int key_num = data_size / value_size;
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < 100; i++) {
int key_ = rand() % key_num+1;
key_ = 1;
std::string key = std::to_string(key_);
std::string value;
status = db->Get(readOptions, key, &value);
assert(status.ok());
break;
}
Env::Default()->SleepForMicroseconds(ttl * 10000);
for (int i = 0; i < 100; i++) {
int key_ = rand() % key_num+1;
key_ = 1;
std::string key = std::to_string(key_);
std::string value;
status = db->Get(readOptions, key, &value);
assert(status.ok() != true);
break;
}
return 0;
}