linux C 设置redis操作超时

linux系统C语言通过hiredis库来连接操作redis,可以通过redisSetTimeout来设置操作的超时时间。

int redisSet Timeout (redisContext *c, const struct timevaltv);

对于建立redis连接的超时需要通过redisConnectWith Timeout来连接redis。

redisContext *redisConnectWith Timeout (const char *ip, int port, const struct timevaltv);

本文通过阻塞连接redis后设置对redis操作的超时,代码如下。

bash 复制代码
编译命令(文件名保存为redis-timeout.cpp)
g++ -g redis-timeout.cpp -o redis-timeout -lhiredis

[root@k8s-node2 redis]# ./redis-timeout 
Command successful
Command successful
cpp 复制代码
#include <iostream>  
#include <hiredis/hiredis.h>  
#include <time.h>
#include <string.h>

bool check_reply(redisContext *c, redisReply* reply) {
    if (reply == NULL) {  
        std::cerr << "Error: " << c->errstr << std::endl;  
        return false;  
    }
  
    // 检查回复是否超时  
    if (reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "OK") == 0) {  
        std::cout << "Command successful" << std::endl;
        return true;
    } else if (reply->type == REDIS_REPLY_ERROR && strstr(reply->str, "timeout") != NULL) {  
        std::cout << "Command timed out" << std::endl;  
    } else {  
        std::cout << "Command failed" << std::endl;  
    }
    return false;
}

int main() {
    redisContext *c = redisConnect("127.0.0.1", 6379);  
    if (c == NULL || c->err) {  
        if (c) {  
            std::cerr << "Error: " << c->errstr << std::endl;  
            redisFree(c);  
        } else {  
            std::cerr << "Can't allocate redis context" << std::endl;  
        }  
        return 1;  
    }  
  
    //"password"改为连接redis需要的密码
    redisReply *reply = static_cast<redisReply*>(redisCommand(c, "auth %s", "password"));
    if(!check_reply(c, reply)) {
        freeReplyObject(reply);
        redisFree(c);
        return 1;
    }
  
    struct timeval tv;
    tv.tv_sec = 0; //单位秒
    tv.tv_usec = 10; //单位微妙
    redisSetTimeout(c, tv); // 设置10微秒超时时间  
    reply = static_cast<redisReply*>(redisCommand(c, "set hello 1"));
    check_reply(c, reply);

    freeReplyObject(reply);
    redisFree(c);

    return 0;  
}
相关推荐
?abc!8 小时前
缓存(3):本地缓存作用 及 数据一致性 实现策略
缓存
欧先生^_^8 小时前
Linux内核可配置的参数
linux·服务器·数据库
问道飞鱼8 小时前
【数据库知识】Mysql进阶-高可用MHA(Master High Availability)方案
数据库·mysql·adb·高可用·mha
tiging8 小时前
centos7.x下,使用宝塔进行主从复制的原理和实践
数据库·mysql·adb·主从复制
wangcheng86998 小时前
Oracle常用函数-日期时间类型
数据库·sql·oracle
zizisuo8 小时前
面试篇:Spring Security
网络·数据库·安全
一只fish8 小时前
MySQL 8.0 OCP 1Z0-908 题目解析(2)
数据库·mysql
StarRocks_labs8 小时前
从InfluxDB到StarRocks:Grab实现Spark监控平台10倍性能提升
大数据·数据库·starrocks·分布式·spark·iris·物化视图
搞不懂语言的程序员9 小时前
Redis的Pipeline和Lua脚本适用场景是什么?使用时需要注意什么?
数据库·redis·lua
王RuaRua9 小时前
[数据结构]5. 栈-Stack
linux·数据结构·数据库·链表