connection.h 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /**************************************************************************
  2. Copyright (c) 2017 sewenew
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. *************************************************************************/
  13. #ifndef SEWENEW_REDISPLUSPLUS_CONNECTION_H
  14. #define SEWENEW_REDISPLUSPLUS_CONNECTION_H
  15. #include <cerrno>
  16. #include <cstring>
  17. #include <memory>
  18. #include <string>
  19. #include <sstream>
  20. #include <chrono>
  21. #include <hiredis/hiredis.h>
  22. #include "errors.h"
  23. #include "reply.h"
  24. #include "utils.h"
  25. namespace sw {
  26. namespace redis {
  27. enum class ConnectionType {
  28. TCP = 0,
  29. UNIX
  30. };
  31. struct ConnectionOptions {
  32. public:
  33. ConnectionOptions() = default;
  34. explicit ConnectionOptions(const std::string &uri);
  35. ConnectionOptions(const ConnectionOptions &) = default;
  36. ConnectionOptions& operator=(const ConnectionOptions &) = default;
  37. ConnectionOptions(ConnectionOptions &&) = default;
  38. ConnectionOptions& operator=(ConnectionOptions &&) = default;
  39. ~ConnectionOptions() = default;
  40. ConnectionType type = ConnectionType::TCP;
  41. std::string host;
  42. int port = 6379;
  43. std::string path;
  44. std::string password;
  45. int db = 0;
  46. bool keep_alive = false;
  47. std::chrono::milliseconds connect_timeout{0};
  48. std::chrono::milliseconds socket_timeout{0};
  49. private:
  50. ConnectionOptions _parse_options(const std::string &uri) const;
  51. ConnectionOptions _parse_tcp_options(const std::string &path) const;
  52. ConnectionOptions _parse_unix_options(const std::string &path) const;
  53. auto _split_string(const std::string &str, const std::string &delimiter) const ->
  54. std::pair<std::string, std::string>;
  55. };
  56. class CmdArgs;
  57. class Connection {
  58. public:
  59. explicit Connection(const ConnectionOptions &opts);
  60. Connection(const Connection &) = delete;
  61. Connection& operator=(const Connection &) = delete;
  62. Connection(Connection &&) = default;
  63. Connection& operator=(Connection &&) = default;
  64. ~Connection() = default;
  65. // Check if the connection is broken. Client needs to do this check
  66. // before sending some command to the connection. If it's broken,
  67. // client needs to reconnect it.
  68. bool broken() const noexcept {
  69. return _ctx->err != REDIS_OK;
  70. }
  71. void reset() noexcept {
  72. _ctx->err = 0;
  73. }
  74. void reconnect();
  75. auto last_active() const
  76. -> std::chrono::time_point<std::chrono::steady_clock> {
  77. return _last_active;
  78. }
  79. template <typename ...Args>
  80. void send(const char *format, Args &&...args);
  81. void send(int argc, const char **argv, const std::size_t *argv_len);
  82. void send(CmdArgs &args);
  83. ReplyUPtr recv();
  84. const ConnectionOptions& options() const {
  85. return _opts;
  86. }
  87. friend void swap(Connection &lhs, Connection &rhs) noexcept;
  88. private:
  89. class Connector;
  90. struct ContextDeleter {
  91. void operator()(redisContext *context) const {
  92. if (context != nullptr) {
  93. redisFree(context);
  94. }
  95. };
  96. };
  97. using ContextUPtr = std::unique_ptr<redisContext, ContextDeleter>;
  98. void _set_options();
  99. void _auth();
  100. void _select_db();
  101. redisContext* _context();
  102. ContextUPtr _ctx;
  103. // The time that the connection is created or the time that
  104. // the connection is used, i.e. *context()* is called.
  105. std::chrono::time_point<std::chrono::steady_clock> _last_active{};
  106. ConnectionOptions _opts;
  107. };
  108. using ConnectionSPtr = std::shared_ptr<Connection>;
  109. enum class Role {
  110. MASTER,
  111. SLAVE
  112. };
  113. // Inline implementaions.
  114. template <typename ...Args>
  115. inline void Connection::send(const char *format, Args &&...args) {
  116. auto ctx = _context();
  117. assert(ctx != nullptr);
  118. if (redisAppendCommand(ctx,
  119. format,
  120. std::forward<Args>(args)...) != REDIS_OK) {
  121. throw_error(*ctx, "Failed to send command");
  122. }
  123. assert(!broken());
  124. }
  125. inline redisContext* Connection::_context() {
  126. _last_active = std::chrono::steady_clock::now();
  127. return _ctx.get();
  128. }
  129. }
  130. }
  131. #endif // end SEWENEW_REDISPLUSPLUS_CONNECTION_H