原文转载于:https://blog.csdn.net/weixin_34381666/article/details/93338116
hiredis是一个非常全面的C语言版redis接口库,支持所有命令、管道与脚本。华为云分布式缓存服务Redis版支持hiredis客户端连接。
使用C语言客户端(hiredis)连接Redis,需要先安装编译环境以及hiredis,以CentOS为例,介绍C客户端环境搭建
第0步:准备工作
华为云上购买1台弹性云服务器ECS(我选了CentOS 6.3),一个分布式缓存实例(DCS for Redis),我选了个单机实例。
注意ECS和缓存实例配置相同的VPC和安全组,确保网络互通。
第1步:安装gcc、make和hiredis
如果系统没有自带编译环境,可以使用yum方式安装。
yum install gcc make
下载并解压hiredis
wget https://github.com/redis/hiredis/archive/master.zip;
进入到解压目录后编译安装
make
make install
安装完成后即可尝试连接。
第2步:连接Redis
关于hiredis的使用,redis官网给了详细的使用介绍。这里举一个简单的例子,介绍连接、密码鉴权、set以及get方法。
编辑连接demo实例,如:
vim connRedis.c
#include #include #include #include int main(int argc, char **argv) { unsigned int j; redisContext *conn; redisReply *reply; if (argc < 3) { printf("Usage: example {instance_ip_address} 6379 {password}"); exit(0); } const char *hostname = argv[1]; const int port = atoi(argv[2]); const char *password = argv[3]; struct timeval timeout = { 1, 500000 }; // 1.5 seconds conn = redisConnectWithTimeout(hostname, port, timeout); if (conn == NULL || conn->err) {if (conn) { printf("Connection error: %s