NebulaGraph CPP Client  release-3.8
SessionPool.h
1 // Copyright (c) 2022 vesoft inc. All rights reserved.
2 //
3 // This source code is licensed under Apache 2.0 License.
4 
5 #pragma once
6 
7 #include <common/datatypes/DataSet.h>
8 
9 #include <cassert>
10 #include <cstddef>
11 #include <mutex>
12 
13 #include "nebula/client/Config.h"
14 #include "nebula/client/ConnectionPool.h"
15 #include "nebula/client/Session.h"
16 
17 namespace nebula {
18 
20  std::string username_;
21  std::string password_;
22  std::vector<std::string> addrs_; // the list of graph addresses
23  std::string spaceName_;
24  // Socket timeout and Socket connection timeout, unit: milliseconds
25  std::uint32_t timeout_{0};
26  // The idleTime of the connection, unit: milliseconds
27  // If connection's idle time is longer than idleTime, it will be delete
28  // 0 value means the connection will not expire
29  std::uint32_t idleTime_{0};
30  std::uint32_t maxSize_{10}; // max size of the session pool. should be adjusted according to the
31  // max threads will be using.
32  std::uint32_t minSize_{1}; // min size of the session pool
33 };
34 
35 class SessionPool {
36  public:
37  SessionPool() = delete;
38  explicit SessionPool(SessionPoolConfig config)
39  : config_(std::move(config)), pool_(new ConnectionPool()) {}
40  SessionPool(const SessionPool &) = delete; // no copy
41  SessionPool(SessionPool &&pool)
42  : config_(std::move(pool.config_)), pool_(std::move(pool.pool_)) {}
43 
44  // initialize session and context
45  // return false when failed, otherwise return true
46  // When return false, the pool is in invalid state, user must destruct it
47  // instead of continue.
48  bool init();
49 
50  // Session pool use fixed space, don't switch space when execute
51  ExecutionResponse execute(const std::string &stmt);
52 
53  ExecutionResponse executeWithParameter(const std::string &stmt,
54  const std::unordered_map<std::string, Value> &parameters);
55 
56  std::string executeJson(const std::string &stmt);
57 
58  std::string executeJsonWithParameter(const std::string &stmt,
59  const std::unordered_map<std::string, Value> &parameters);
60 
61  private:
62  std::pair<Session, bool> getIdleSession() {
63  std::lock_guard<std::mutex> l(m_);
64  if (idleSessions_.empty()) {
65  return std::make_pair(Session(), false);
66  }
67  auto session = std::move(idleSessions_.front());
68  idleSessions_.pop_front();
69  return std::make_pair(std::move(session), true);
70  }
71 
72  void giveBack(Session &&session) {
73  std::lock_guard<std::mutex> l(m_);
74  idleSessions_.emplace_back(std::move(session));
75  }
76 
77  SessionPoolConfig config_;
78  std::unique_ptr<ConnectionPool> pool_;
79  // destruct session before pool
80  std::mutex m_;
81  std::list<Session> idleSessions_;
82 };
83 
84 } // namespace nebula