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;  
}
相关推荐
爱吃java的羊儿17 分钟前
Linux环境下卸载Redis
linux·运维·redis
LeslieMhb20 分钟前
基于redis的分布式锁
redis·分布式·junit
StrivePeng23 分钟前
Spring Data Redis + Redis数据缓存学习笔记
spring boot·redis·笔记·spring·缓存
zengson_g1 小时前
PostgreSQL 中如何处理数据的并发读写和锁等待超时?
数据库·sql·postgresql
草青工作室1 小时前
pgsql-使用dump命令制作数据库结构、数据快速备份bat脚本
数据库
Black_Cat_yyds1 小时前
redis-缓存三剑客
数据库·redis·缓存
结衣结衣.2 小时前
深度刨析程序中的指针
java·c语言·数据库·经验分享·笔记·算法
ydy22009502 小时前
Redis-基础概念
数据库·redis·缓存
德乐懿2 小时前
为什么MySQL会选择B+树作为索引
数据库·b树·mysql
FirstTalent3 小时前
从MySQL切换PostgreSQL后,改动的地方,注意事项!!!
数据库·mysql·postgresql