#include "leveldb/env.h"
|
|
#include "leveldb/db.h"
|
|
#include "ctime"
|
|
#include <iostream>
|
|
#include <cstdlib>
|
|
|
|
|
|
using namespace leveldb;
|
|
|
|
constexpr int value_size = 2048;
|
|
constexpr int data_size = 4096 << 1;
|
|
|
|
Status OpenDB(std::string dbName, DB **db) {
|
|
Options options;
|
|
options.create_if_missing = true;
|
|
return DB::Open(options, dbName, db);
|
|
}
|
|
|
|
void InsertData(DB *db, uint64_t ttl/* second */) {
|
|
printf("-----inserting-----\n");
|
|
Status status;
|
|
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;
|
|
int key_ = i+1;
|
|
std::string key = std::to_string(key_);
|
|
std::string value(value_size, 'a');
|
|
status = db->Put(writeOptions, key, value, ttl);
|
|
assert(status.ok());
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
int main(int argc, char** argv) {
|
|
DB *db;
|
|
if(OpenDB("testdb", &db).ok() == false) {
|
|
std::cerr << "open db failed" << std::endl;
|
|
abort();
|
|
}
|
|
|
|
uint64_t ttl = 3;
|
|
|
|
InsertData(db, ttl);
|
|
|
|
printf("-----seeking-----\n");
|
|
ReadOptions readOptions;
|
|
Status status;
|
|
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;
|
|
int key_ = i+1;
|
|
std::string key = std::to_string(key_);
|
|
std::string value;
|
|
status = db->Get(readOptions, key, &value);
|
|
assert(status.ok());
|
|
}
|
|
|
|
Env::Default()->SleepForMicroseconds(ttl * 1000000);
|
|
|
|
for (int i = 0; i < key_num; i++) {
|
|
int key_ = rand() % key_num+1;
|
|
std::string key = std::to_string(key_);
|
|
std::string value;
|
|
status = db->Get(readOptions, key, &value);
|
|
assert(status.IsNotFound());
|
|
}
|
|
printf("success!\n");
|
|
}
|