#include "leveldb/env.h"
|
|
#include "leveldb/db.h"
|
|
#include "ctime"
|
|
#include <iostream>
|
|
#include <cstdlib>
|
|
#include "gtest/gtest.h"
|
|
|
|
using namespace leveldb;
|
|
|
|
constexpr int value_size = 2048;
|
|
constexpr int data_size = 2048 << 2;
|
|
|
|
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 */, int vsize = 1/*插不同长度的value*/) {
|
|
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(vsize, 'a');
|
|
status = db->Put(writeOptions, key, value, ttl);
|
|
assert(status.ok());
|
|
}
|
|
}
|
|
|
|
void GetData(DB *db, bool isTimeout) {
|
|
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);
|
|
if(isTimeout) assert(status.IsNotFound());
|
|
else{
|
|
assert(status.ok());
|
|
std::cout << value << std::endl;
|
|
}
|
|
}
|
|
}
|
|
|
|
void TimeOut() {
|
|
DB *db;
|
|
printf("-----opening-----\n");
|
|
if(OpenDB("testdb", &db).ok() == false) {
|
|
std::cerr << "open db failed" << std::endl;
|
|
abort();
|
|
}
|
|
|
|
uint64_t ttl = 3;
|
|
|
|
InsertData(db, ttl);
|
|
GetData(db, false);
|
|
|
|
Env::Default()->SleepForMicroseconds(ttl * 1000000);
|
|
GetData(db, true);
|
|
|
|
delete(db);
|
|
printf("-----closing-----\n");
|
|
|
|
// printf("-----recovery-----\n");
|
|
// if(OpenDB("testdb", &db).ok() == false) {
|
|
// std::cerr << "open db failed" << std::endl;
|
|
// abort();
|
|
// }
|
|
// GetData(db, true);
|
|
printf("success!\n");
|
|
}
|
|
|
|
void GetEarlierData() {
|
|
DB *db;
|
|
printf("-----opening-----\n");
|
|
if(OpenDB("testdb", &db).ok() == false) {
|
|
std::cerr << "open db failed" << std::endl;
|
|
abort();
|
|
}
|
|
|
|
uint64_t ttl1 = 3;
|
|
uint64_t ttl2 = 5;
|
|
|
|
InsertData(db, ttl2);
|
|
InsertData(db, ttl1, 2);
|
|
|
|
//都没过期先找到后插的
|
|
Env::Default()->SleepForMicroseconds(1 * 1000000);
|
|
GetData(db, false);
|
|
|
|
//再找到前一次
|
|
Env::Default()->SleepForMicroseconds(3 * 1000000);
|
|
GetData(db, false);
|
|
|
|
delete(db);
|
|
printf("-----closing-----\n");
|
|
printf("success!\n");
|
|
}
|
|
|
|
int main(int argc, char** argv) {
|
|
GetEarlierData();
|
|
}
|