前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >hiredis从安装到实操,带 API 详解

hiredis从安装到实操,带 API 详解

作者头像
看、未来
发布2021-12-20 19:51:44
2.3K0
发布2021-12-20 19:51:44
举报

文章目录

花个两分钟跟我一起配置hiredis

当我们下载了最新版redis的时候,其实就已经自带了C++版本的操作库,只不过有些人没发现罢了。

进入到deps->hiredis目录下(在你的redis解压目录下有deps)

然后:make install

一步到位。

其实连测试函数他们都给你准备好了,在hedis文件夹中还有个文件夹,example,里面有个example.c文件。

这样编译,如果不会的话:首先需要把里面的头文件改一下:#include<hiredis/hiredis.h> 编译的时候记得带上依赖项: gcc example.c -o example -L/usr/local/lib -lhiredis

当你运行的时候,(别给我说你不会运行:./example)如果不出意外,会跟你说依赖项找不着。 正常,教你一个治标的办法:

在/etc/ld.so.conf.d/目录下新建文件usr-libs.conf,内容是:/usr/local/lib

然后使用命令/sbin/ldconfig更新一下配置即可。

这东西配置完,你虚拟机重启之后就没了,永久配置好像在我的另一篇博客里有,动态库专栏下。

最后的运行效果:

在这里插入图片描述
在这里插入图片描述

redis的C/C++ API

建立连接

代码语言:javascript
复制
redisContext* pRedisContext=(redisContext*)redisConnect(ip, port);//建立连接

参数释义: 该函数用来连接redis数据库, 两个参数分别是redis数据库的ip和端口,端口号一般为6379。

如果是密码连接,在连接后还要输入密码登录:

代码语言:javascript
复制
reply = (redisReply *)redisCommand(pRedisContext, "AUTH %s", redis_password);//密码访问

写数据库

代码语言:javascript
复制
std::string key, value;
...
redisReply *reply;
reply = (redisReply *)redisCommand(redisContext,"SET %s %s", key.c_str(), value.c_str());//写

这里要注意,对于序列化的结构数据,string中保存的是二进制数据,c_str()方法返回的c字符串被二进制0值截断,会造成数据不完整,而hiredis提供%b作为格式化二进制的方法,需要提供起始地址和长度:

代码语言:javascript
复制
reply = (redisReply *)redisCommand(redisContext, "SET %s %b", key.c_str(), value.data(), value.length());
//写长byte流

读数据库

代码语言:javascript
复制
redisReply *reply;
reply = (redisReply *)redisCommand(redisContext,"GET %s", key.c_str());//读
std::cout<<reply->str;

释放内存

代码语言:javascript
复制
void freeReplyObject(void *reply);

释放redisCommand执行后返回的的redisReply所占用的内存。

释放连接

代码语言:javascript
复制
void redisFree(redisContext *c)

释放redisConnect()所产生的连接。

实操代码示例

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<hiredis/hiredis.h>

int main(int argc, char **argv) {
    unsigned int j, isunix = 0;
    redisContext *c;		
    redisReply *reply;		:
    const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";

    if (argc > 2) {
        if (*argv[2] == 'u' || *argv[2] == 'U') {
            isunix = 1;
            /* in this case, host is the path to the unix socket */
            printf("Will connect to unix socket @%s\n", hostname);
        }
    }

    int port = (argc > 2) ? atoi(argv[2]) : 6379;
    
	struct timeval timeout = { 1, 500000 }; // 1.5 seconds
    if (isunix) {
        c = redisConnectUnixWithTimeout(hostname, timeout);
        //该函数用来连接redis数据库, 两个参数分别是redis数据库的ip和端口,端口号一般为6379。
    } else {
        c = redisConnectWithTimeout(hostname, port, timeout);
    }
    if (c == NULL || c->err) {
        if (c) {
            printf("Connection error: %s\n", c->errstr);	
            redisFree(c);	//释放redisConnect()所产生的连接。
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
        exit(1);
    }

	 /* PING server */
    reply = redisCommand(c,"PING");	
    //该函数用于执行redis数据库中的命令,第一个参数为连接数据库返回的redisContext,剩下的参数为变参.。
	//此函数的返回值为void*,但是一般会强制转换为redisReply类型,以便做进一步的处理。
    
    printf("PING: %s\n", reply->str);
    freeReplyObject(reply);	//释放redisCommand执行后返回的的redisReply所占用的内存。

	 /* Set a key */
    reply = redisCommand(c,"SET %s %s", "foo", "hello world");
    printf("SET: %s\n", reply->str);
    freeReplyObject(reply);

    /* Set a key using binary safe API */
    reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
    printf("SET (binary API): %s\n", reply->str);
    freeReplyObject(reply);

    /* Try a GET and two INCR */
    reply = redisCommand(c,"GET foo");
    printf("GET foo: %s\n", reply->str);
    freeReplyObject(reply);

    reply = redisCommand(c,"INCR counter");
    printf("INCR counter: %lld\n", reply->integer);
    freeReplyObject(reply);
    /* again ... */
    reply = redisCommand(c,"INCR counter");
    printf("INCR counter: %lld\n", reply->integer);
    freeReplyObject(reply);

    /* Create a list of numbers, from 0 to 9 */
    reply = redisCommand(c,"DEL mylist");
    freeReplyObject(reply);
    for (j = 0; j < 10; j++) {
        char buf[64];
        snprintf(buf,64,"%u",j);
        reply = redisCommand(c,"LPUSH mylist element-%s", buf);
        freeReplyObject(reply);
    }

    /* Let's check what we have inside the list */
    reply = redisCommand(c,"LRANGE mylist 0 -1");
    if (reply->type == REDIS_REPLY_ARRAY) {
        for (j = 0; j < reply->elements; j++) {
            printf("%u) %s\n", j, reply->element[j]->str);
        }
    }
    freeReplyObject(reply);

    /* Disconnects and frees the context */
    redisFree(c);

    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-12-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 花个两分钟跟我一起配置hiredis
  • redis的C/C++ API
    • 建立连接
      • 写数据库
        • 读数据库
          • 释放内存
            • 释放连接
            • 实操代码示例
            相关产品与服务
            云数据库 Redis
            腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档