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;  
}
相关推荐
YGGP23 分钟前
MySQL 的事务
数据库·mysql
Code额2 小时前
缓存 “三剑客”
redis·缓存
珹洺2 小时前
C++从入门到实战(十)类和对象(最终部分)static成员,内部类,匿名对象与对象拷贝时的编译器优化详解
java·数据结构·c++·redis·后端·算法·链表
一 乐2 小时前
网红酒店|基于java+vue的网红酒店预定系统(源码+数据库+文档)
java·开发语言·数据库·毕业设计·论文·springboot·网红酒店预定系统
Alfadi联盟 萧瑶3 小时前
Python-用户账户与应用程序样式
数据库·sqlite
影子24017 小时前
Navicat导出mysql数据库表结构说明到excel、word,单表导出方式记录
数据库·mysql·excel
java_heartLake8 小时前
PostgreSQL15深度解析(从15.0-15.12)
数据库·postgresql
nuc-1279 小时前
sqli-labs学习记录8
数据库·学习·sqli-labs
余华余华10 小时前
计算机等级考试数据库三级(笔记3)
服务器·数据库·oracle
南風_入弦11 小时前
Oracle logminer详解
数据库·oracle·恢复