作者: 韩晨旭 10225101440 李畅 10225102463
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 rivejä
1.6 KiB

2 kuukautta sitten
  1. #include "leveldb/db.h"
  2. #include "leveldb/filter_policy.h"
  3. #include <iostream>
  4. #include <cstdlib>
  5. #include <ctime>
  6. using namespace leveldb;
  7. constexpr int value_size = 2048;
  8. constexpr int data_size = 256 << 20;
  9. // 3. 数据管理(Manifest/创建/恢复数据库)
  10. Status OpenDB(std::string dbName, DB **db) {
  11. Options options;
  12. options.create_if_missing = true;
  13. options.filter_policy = NewBloomFilterPolicy(10);
  14. return DB::Open(options, dbName, db);
  15. }
  16. // 1. 存储(数据结构与写入)
  17. // 4. 数据合并(Compaction)
  18. void InsertData(DB *db) {
  19. WriteOptions writeOptions;
  20. int key_num = data_size / value_size;
  21. srand(static_cast<unsigned int>(time(0)));
  22. for (int i = 0; i < key_num; i++) {
  23. int key_ = rand() % key_num+1;
  24. std::string key = std::to_string(key_);
  25. std::string value(value_size, 'a');
  26. db->Put(writeOptions, key, value);
  27. }
  28. }
  29. // 2. 数据访问(如何读数据)
  30. void GetData(DB *db, int size = (1 << 30)) {
  31. ReadOptions readOptions;
  32. int key_num = data_size / value_size;
  33. // 点查
  34. srand(static_cast<unsigned int>(time(0)));
  35. for (int i = 0; i < 100; i++) {
  36. int key_ = rand() % key_num+1;
  37. std::string key = std::to_string(key_);
  38. std::string value;
  39. db->Get(readOptions, key, &value);
  40. }
  41. // 范围查询
  42. Iterator *iter = db->NewIterator(readOptions);
  43. iter->SeekToFirst();
  44. while (iter->Valid()) {
  45. iter->Next();
  46. }
  47. delete iter;
  48. }
  49. int main() {
  50. DB *db;
  51. if(OpenDB("testdb", &db).ok()) {
  52. InsertData(db);
  53. delete db;
  54. }
  55. if(OpenDB("testdb", &db).ok()) {
  56. GetData(db);
  57. delete db;
  58. }
  59. return 0;
  60. }