NebulaGraph CPP Client  release-3.8
ConnectionPool.h
1 /* Copyright (c) 2020 vesoft inc. All rights reserved.
2  *
3  * This source code is licensed under Apache 2.0 License.
4  */
5 
6 #pragma once
7 
8 #include <list>
9 #include <memory>
10 #include <mutex>
11 #include <thread>
12 
13 #include "nebula/client/Config.h"
14 #include "nebula/client/Connection.h"
15 #include "nebula/client/Session.h"
16 
17 namespace nebula {
18 
20  public:
21  ~ConnectionPool();
22 
23  void init(const std::vector<std::string> &addresses, const Config &config);
24 
25  void close();
26 
27  Session getSession(const std::string &username,
28  const std::string &password,
29  bool retryConnect = true);
30 
31  Connection getConnection();
32 
33  void giveBack(Connection &&conn);
34 
35  std::size_t size() const {
36  std::lock_guard<std::mutex> l(lock_);
37  return conns_.size();
38  }
39 
40  private:
41  // The count may can't perform if can't create enough valid connection
42  void newConnection(std::size_t cursor, std::size_t count);
43 
44  std::size_t nextCursor() {
45  return cursor_ >= address_.size() ? cursor_ = 0 : cursor_++;
46  }
47 
48  std::size_t cursor_{0};
49  // host, port
50  std::vector<std::pair<std::string, int32_t>> address_;
51  Config config_;
52 
53  mutable std::mutex lock_;
54  std::list<Connection> conns_;
55 };
56 
57 } // namespace nebula