1 #include <hiredis/hiredis.h> 2 2 #include <iostream> 3 3 #include <string> 4 4 #include <stdio.h> 5 5 #include <stdlib.h> 6 6 #include <string.h> 7 7 #include <unistd.h> 8 8 9 9 bool do_string(redisContext*& pConn, const char* cmd) 10 10 { 11 11 12 12 redisReply* res = (redisReply*)redisCommand(pConn, cmd); 13 13 14 14 if(NULL == res ) 15 15 { 16 16 std::cout<<"Execut cmd failure "; 17 17 return false; 18 18 } 19 19 20 20 if(res->type == REDIS_REPLY_ERROR) 21 21 { 22 22 std::cout<<"Failed to execute cmd: "<<cmd<<" error:"<<res->str<<" "; 23 23 freeReplyObject(res); 24 24 return false; 25 25 } 26 26 27 27 freeReplyObject(res); 28 28 std::cout<<"Succed to execute cmd:"<<cmd<<" "; 29 29 30 30 31 31 return true; 32 32 } 33 33 void test_string(redisContext*& pConn) 34 35 { 35 36 const char* cmd[]={ 36 37 "set gxq 2.12", 37 38 "strlen gxq", 38 39 "gets gxq"}; 39 40 40 41 for(size_t i=0; i<3; ++i) 41 42 { 42 43 do_string(pConn, cmd[i]); 43 44 usleep(20*1000); 44 45 } 45 46 46 47 } 47 48 48 49 int main(int argc, char** argv) 49 50 { 50 51 struct timeval timeout={2,0};// 51 52 52 53 redisContext* pRedisContext = (redisContext*)redisConnectWithTimeout("127.0.0.1",6379,timeout); 53 54 54 55 if (NULL == pRedisContext || pRedisContext->err) 55 56 { 56 57 if(pRedisContext) 57 58 std::cout<<"connect error:"<<pRedisContext->errstr<<" "; 58 59 else 59 60 std::cout<<"connect error: can't allcoate redis context."<<" "; 60 61 61 62 return -1; 62 63 } 63 64 64 65 65 66 test_string(pRedisContext); 66 67 67 68 redisFree(pRedisContext); 68 69 69 70 return 0; 70 71 71 72 } 72