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;  
}
相关推荐
眠りたいです26 分钟前
Mysql常用内置函数,复合查询及内外连接
linux·数据库·c++·mysql
paopaokaka_luck1 小时前
智能推荐社交分享小程序(websocket即时通讯、协同过滤算法、时间衰减因子模型、热度得分算法)
数据库·vue.js·spring boot·后端·websocket·小程序
He.ZaoCha1 小时前
函数-1-字符串函数
数据库·sql·mysql
二当家的素材网1 小时前
Centos和麒麟系统如何每天晚上2点10分定时备份达梦数据库
linux·数据库·centos
白仑色2 小时前
Oracle 存储过程、函数与触发器
数据库·oracle·数据库开发·存储过程·plsql编程
头发那是一根不剩了3 小时前
Spring Boot 多数据源切换:AbstractRoutingDataSource
数据库·spring boot·后端
草履虫建模3 小时前
Redis:高性能内存数据库与缓存利器
java·数据库·spring boot·redis·分布式·mysql·缓存
A-刘晨阳4 小时前
【Linux】Redis 6.2.6 的二进制部署【适用于多版本】
linux·运维·redis
泊浮目4 小时前
未来数据库硬件-计算篇
数据库·云计算·操作系统
靖顺4 小时前
【OceanBase诊断调优】—— 执行计划显示分区 PARTITIONS[P0SP9] 如何查询是哪个分区?
数据库·oracle·oceanbase