tencent cloud

文档反馈

C 连接示例

最后更新时间:2021-11-30 16:24:55

运行前必备:
下载并安装 hiredis

示例代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
int main(int argc, char **argv) {
   unsigned int j;
   redisContext *c;
   redisReply *reply;

if (argc < 4) {
     printf("Usage: 192.xx.xx.195 6379 instance_id password\n");
     exit(0);
   }
   const char *hostname = argv[1];
   const int port = atoi(argv[2]);
   const char *instance_id = argv[3];
   const char *password    = argv[4];


   struct timeval timeout = { 1, 500000 }; // 1.5 seconds
   c = redisConnectWithTimeout(hostname, port, timeout);
   if (c == NULL || c->err) {
       if (c) {
           printf("Connection error: %s\n", c->errstr);
           redisFree(c);
       } else {
           printf("Connection error: can't allocate redis context\n");
       }
       exit(1);
   }

/* AUTH */
   reply = redisCommand(c, "AUTH %s", password);
   printf("AUTH: %s\n", reply->str);
   freeReplyObject(reply);
    /* PING server */
   reply = redisCommand(c,"PING");
   printf("PING: %s\n", reply->str);
   freeReplyObject(reply);
    /* Set a key */
   reply = redisCommand(c,"SET %s %s", "name", "credis_test");
   printf("SET: %s\n", reply->str);
   freeReplyObject(reply);
    /* Try a GET  */
   reply = redisCommand(c,"GET name");
   printf("GET name: %s\n", reply->str);
   freeReplyObject(reply);
    /* Disconnects and frees the context */
   redisFree(c);
    return 0;
}

运行结果

联系我们

联系我们,为您的业务提供专属服务。

技术支持

如果你想寻求进一步的帮助,通过工单与我们进行联络。我们提供7x24的工单服务。

7x24 电话支持