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;  
}
相关推荐
小二·9 小时前
Redis 内存溢出(OOM)排查与恢复实战
数据库·redis·bootstrap
pqk6V6Vep9 小时前
Redis 分布式锁进阶第一篇讲解
数据库·redis·分布式
giaz14n9X10 小时前
Redis 分布式锁进阶第六十一篇
数据库·redis·分布式
是一个Bug10 小时前
MongoDB:像搭积木一样存数据
数据库·mongodb
ULIi096kr10 小时前
MySQL解决Too many connections报错:连接数爆满排查、优化与永久解决方案
数据库·mysql·adb
SL-staff11 小时前
(一)数据源配置 —— JVS-Rules规则引擎 V2.5 操作说明介绍
数据库·jar·规则引擎·数据源·jvs-rules·api 接口·jvs低代码
摇滚侠12 小时前
Spring 零基础入门到进阶 基于 XML 管理 Bean 14-28
xml·数据库·spring
Metaphor69212 小时前
使用 Python 给 PDF 设置背景色或背景图
数据库·python·pdf
Gauss松鼠会12 小时前
【GaussDB】GaussDB重要通信参数汇总
服务器·网络·数据库·sql·性能优化·gaussdb·经验总结
睡不醒男孩03082312 小时前
第五篇:2026年企业级 PostgreSQL 高可用方案深度横评:Patroni vs. CLup 架构与可靠性全面对决
数据库·postgresql·架构