最近在国内论坛上没找到使用hiredis存储结构体像样的demo,更没有使用结构体同时作为key和value的demo(起码我没找到),所以自己记录一下自己的成果
#include <stdio.h>
#include <string.h>
#include <hiredis/hiredis.h>
typedef struct {
char name[10];
char myStr[20];
} mytest;
void test(void)
{
redisContext *context = redisConnect("127.0.0.1", 6379);//默认端口,本机redis-server服务开启
if(context->err) {
//连接失败
redisFree(context);
printf("connect redisServer err:%s\n", context->errstr);
return ;
}
printf("connect success\n");
mytest test={0};
memset(test.name, '\0', 10);
strcpy(test.myStr, "llllll");
mytest key={0};
//strcpy(key.name, "123");
strcpy(key.myStr, "strstr");
char *key2 = strdup("test_key");
printf("start set key value\n");
redisReply *reply = (redisReply*)redisCommand(context, "SET %b %b",&key,sizeof(key),&test, sizeof(test));
freeReplyObject(reply);
reply = redisCommand(context, "GET %b", &key, sizeof(key));
mytest *result = (mytest *)reply->str;
printf("%s\n",result->name);
printf("%s\n",result->myStr);
freeReplyObject(reply);
}
int main(void)
{
test();
return 0;;
}
如果需要key为字符串类型的,只需要把key改为char数组,删除取地址符,value仍然不变即可