C++ call hiredis library to operate redis explanation

   First download and compile hiredis, visit https://github.com/redis/hiredis to download hiredis library source code, my compiling environment is ubuntu14, after decompressing hiredis source code, enter the source directory in the terminal, and then enter the make command to compile, after compiling Will get static and dynamic library files: libhiredis.a / libhiredis.so, and then combine the header files to use redis in the project. In the project, I use the static library libhiredis.a and the header files: hiredis.h, read.h, sds.h. Whether to use a static library or a dynamic library, it varies from person to person.
1. The following is an example of connecting to redis based on server ip, port and password:
void redisConnect (string serverAddr, uint16_t port, string password)
{     LOG_INFO << "Start connecting to redis server..." << serverAddr << ":" << port;     // connection     timeval timeout = {3, 500000 };     redis_ctx_ = redisConnectWithTimeout(serverAddr.c_str(), port, timeout);     if (redis_ctx_ == NULL || redis_ctx_->err)     {         if (redis_ctx_ != NULL)         {

 







            LOG_INFO << "Connection error: "<< redis_ctx_->errstr;
            redisFree (redis_ctx_);
            redis_ctx_ = NULL;
        }
        else
        {             LOG_INFO << "Connection error: redis context initialization error";         }         // todo delays 30 seconds to reconnect to redis Server         return;     }     else     {         LOG_INFO << "Connected to the redis server successfully..." << serverAddr << ":" << port;     }     // Verify     redis_reply_ = (redisReply * )redisCommand (redis_ctx_, "auth %s", password.c_str());     if (redis_reply_->type == REDIS_REPLY_ERROR)     {         LOG_INFO << "Authentication failure";


 







 





    }
    else
    {         LOG_INFO << "Authentication success";     } freeReplyObject (redis_reply_); }         Combined with the output log, the code is easy to understand. The above 30-second delay reconnection mechanism needs to be designed by yourself. 2. Distribute data to the redis server (redis publish and subscribe mode):   mainly call redisCommand(), fill in the command parameters in the specified format, and execute various redis commands. I won't list them all here. However, the performance of hiredis in practical applications remains to be verified. void distributeRedisMessage(const string &content, const string &topic) {     if (redis_ctx_ == NULL)     {         return;     }     redis_reply_ = (redisReply *)redisCommand(redis_ctx_, "publish %s %s", topic.c_str(), content.c_str ());     if (redis_reply_ != NULL)     {


   










 



        if (redis_reply_->type == REDIS_REPLY_ERROR)
        {             LOG_INFO << "Command transmission failed: "<< redis_reply_->type <<" "<< redis_reply_->str;         }         freeReplyObject(redis_reply_);     }     else     {         LOG_INFO <<" connection to the server to redis command transmission failed: "<< redis_ctx _-> ERR <<" "<< redis_ctx _-> the errstr;         redisFree (redis_ctx_);         redis_ctx_ = NULL;         // TODO delay of 30 seconds before reconnecting the server redis     } }     course , The above are all encapsulated methods, and remember to declare redisContext *redis_ctx_ and redisReply *redis_reply_, and remember to initialize.     I also write some java server programs at work. I also use jedis. By the way, I would like to mention a jedis error that I encountered a few days ago, which is very difficult to check. The error message is as follows:









 





Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool. I checked it and found out that it was a configuration file problem.
It mainly includes the following four methods:
1. redisContext* redisConnect(const char *ip, int port)
   This function is used to connect to the redis database. The two parameters are the ip and port of the redis database. The port number is generally 6379. Similarly, a function is provided for connection timeout limitation, namely
   redisContext* redisConnectWithTimeout(const char *ip, int port, timeval tv).
2. void *redisCommand(redisContext *c, const char *format...)
   This function is used to execute commands in the redis database. The first parameter is the redisContext returned by connecting to the database, and the remaining parameters are variable parameters, just like C The prinf() function in the language.
   The return value of this function is void*, but it will generally be cast to the redisReply type for further processing.

3. void freeReplyObject(void *reply)
   releases the memory occupied by the redisReply returned after the redisCommand is executed.

4. void redisFree(redisContext *c)
   releases the connection created by redisConnect().
   
   C++ use hiredis library to operate redis explanation

Guess you like

Origin blog.csdn.net/qq_20853741/article/details/113487386