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;  
}
相关推荐
罗光记3 分钟前
Quantinuum 发布新型量子计算机“Helios“
数据库·经验分享·其他·百度·twitter
友友马23 分钟前
『 数据库 』MySQL索引深度解析:从数据结构到B+树的完整指南
数据库·mysql
SelectDB37 分钟前
替换 ClickHouse,查询并发提升 7 倍!高途教育基于阿里云 SelectDB 构建秒级实时报表
数据库·apache
JamSlade44 分钟前
优化用户体验的小点:乐观更新链路 双数据库查询
数据库·ux
一 乐1 小时前
个人博客|博客app|基于Springboot+微信小程序的个人博客app系统设计与实现(源码+数据库+文档)
java·前端·数据库·spring boot·后端·小程序·论文
小二·1 小时前
用 eBPF 实现 MySQL 慢查询实时追踪(终极实战版):零侵入、毫秒级、全上下文捕获
数据库·mysql·adb
云飞云共享云桌面1 小时前
三维设计办公资源如何共享集中和安全管控?
运维·服务器·数据库·安全·自动化·制造
百锦再2 小时前
大型省级政务平台采用金仓数据库(KingbaseES)
开发语言·数据库·后端·rust·eclipse
过客随尘2 小时前
Redis主从同步以及Redis-Shake数据同步实战
redis·云原生
Chloeis Syntax3 小时前
MySQL初阶学习日记(2)--- 数据库的数据类型和表的操作
数据库·学习·mysql