redis.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * @Description:
  3. * @Version: 1.0
  4. * @Autor: zhuyijun
  5. * @Date: 2021-11-17 13:05:50
  6. * @LastEditTime: 2021-11-17 13:05:50
  7. */
  8. #ifndef _REDIS_H_
  9. #define _REDIS_H_
  10. #include <hiredis/hiredis.h>
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <iostream>
  14. #include <string>
  15. class Redis {
  16. public:
  17. Redis() {}
  18. ~Redis() {
  19. this->_connect = NULL;
  20. this->_reply = NULL;
  21. }
  22. bool connect(std::string host, int port) {
  23. this->_connect = redisConnect(host.c_str(), port);
  24. if (this->_connect != NULL && this->_connect->err) {
  25. printf("connect error: %s\n", this->_connect->errstr);
  26. return 0;
  27. }
  28. return 1;
  29. }
  30. std::string get(std::string key) {
  31. this->_reply =
  32. (redisReply*)redisCommand(this->_connect, "GET %s", key.c_str());
  33. std::string str = this->_reply->str;
  34. freeReplyObject(this->_reply);
  35. return str;
  36. }
  37. void set(std::string key, std::string value) {
  38. redisCommand(this->_connect, "SET %s %s", key.c_str(), value.c_str());
  39. }
  40. private:
  41. redisContext* _connect;
  42. redisReply* _reply;
  43. };
  44. #endif //_REDIS_H_