123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- #include "FromRedis.h"
- #include "fmtlog.h"
- FromRedis::FromRedis()
- {
- }
- FromRedis::~FromRedis()
- {
- }
- /* 设置IP和端口 */
- void FromRedis::setRedisIPAndPort(const std::string& ip, int port)
- {
- m_redisIP = ip;
- m_redisPort = port;
- }
- /* 设置密码 */
- void FromRedis::setRedisPassword(const std::string& password)
- {
- m_redisPassword = password;
- }
- /* 连接Redis */
- bool FromRedis::connectRedis()
- {
- if(m_redisContext != nullptr)
- {
- redisFree(m_redisContext);
- m_redisContext = nullptr;
- }
- if(m_redisIP.empty())
- {
- FMTLOG_ERROR( "Redis IP is empty");
- return false;
- }
- /* 连接Redis */
- m_redisContext = redisConnect(m_redisIP.c_str(), m_redisPort);
- if( (m_redisContext == nullptr) || ( m_redisContext->err != 0) )
- {
- FMTLOG_ERROR( "Connect redis failed:{}", m_redisContext->errstr);
- return false;
- }
- FMTLOG_INFO("Connect redis success");
- /* 登录认证 */
- if(!m_redisPassword.empty())
- {
- if(!authRedis(m_redisPassword))
- {
- FMTLOG_ERROR( "Auth redis failed");
- return false;
- }
- // FMTLOG_INFO( "Auth redis success");
- }
- return true;
- }
- /* 断开Redis连接 */
- void FromRedis::disConnectRedis()
- {
- if(m_redisContext != nullptr)
- {
- redisFree(m_redisContext);
- m_redisContext = nullptr;
- }
- }
- /* 获取redis中的String数据 */
- bool FromRedis::getRedisString(const std::string& key, std::string& value)
- {
- if(m_redisContext == nullptr)
- {
- FMTLOG_ERROR( "Redis no connect");
- return false;
- }
- /* 获取数据 */
- auto reply = (redisReply*)redisCommand(m_redisContext, "GET %s", key.c_str());
- // auto reply = (redisReply*)redisCommand(m_redisContext, "GET 113:P100104000");
- if(reply == nullptr)
- {
- FMTLOG_ERROR( "Get redis string data failed");
- return false;
- }
- if(reply->type != REDIS_REPLY_STRING)
- {
- FMTLOG_ERROR( "Get redis data failed, type is not string, type: {}, error str: {}", reply->type, reply->str);
- freeReplyObject(reply);
- return false;
- }
- value = reply->str;
- freeReplyObject(reply);
- return true;
- }
- /* 登录认证Redis,这个需要在连接成功后调用 */
- bool FromRedis::authRedis(const std::string& password)
- {
- if(m_redisContext == nullptr)
- {
- FMTLOG_ERROR( "Redis no connect");
- return false;
- }
- auto reply = (redisReply*)redisCommand(m_redisContext, "AUTH %s", password.c_str());
- if(reply == nullptr)
- {
- FMTLOG_ERROR( "Redis Auth failed");
- return false;
- }
- /* 判断返回值 */
- if( reply->type == REDIS_REPLY_STATUS && strcasecmp(reply->str, "OK") == 0)
- {
- FMTLOG_INFO( "Redis Auth success");
- freeReplyObject(reply);
- return true;
- }
- else
- {
- FMTLOG_ERROR( "Redis Auth failed:{}", reply->str);
- freeReplyObject(reply);
- return false;
- }
- }
|