redis服务C语言客户端hiredis使用笔记

194 阅读1分钟

环境

  • macxos 13.4.1
  • redis 6

hiredis编译

git clone git@github.com:redis/hiredis.git

cd hiredis

make

make install

make install 后生成的文件:

cd /usr/local/lib

ll libhiredis*
-rwxr-xr-x  1 morningcat  staff   124K 11  9 22:33 libhiredis.1.2.1-dev.dylib
-rw-r--r--  1 morningcat  staff   323K 11  9 22:33 libhiredis.a
lrwxr-xr-x  1 morningcat  admin    26B 11  9 22:34 libhiredis.dylib -> libhiredis.1.2.1-dev.dylib
lrwxr-xr-x  1 morningcat  admin    26B 11  9 22:34 libhiredis.dylib.1 -> libhiredis.1.2.1-dev.dylib

cd /usr/local/include

ll hiredis/*
-rw-r--r--  1 morningcat  staff   3.1K 11  9 02:24 hiredis/alloc.h
-rw-r--r--  1 morningcat  staff   6.1K 11  9 02:24 hiredis/async.h
-rw-r--r--  1 morningcat  staff    14K 11  9 02:24 hiredis/hiredis.h
-rw-r--r--  1 morningcat  staff   4.8K 11  9 02:24 hiredis/read.h
-rw-r--r--  1 morningcat  staff   9.0K 11  9 02:24 hiredis/sds.h
-rw-r--r--  1 morningcat  staff   4.3K 11  9 02:24 hiredis/sockcompat.h

启动redis

cd /usr/local/Cellar/redis/6.0.10/bin

./redis-server redis.conf &

查看密码

cat redis.conf | grep requirepass

hiredis 基本使用

#include <stdio.h>
#include <hiredis/hiredis.h>

int main()
{
    redisReply *reply;
    const char *host = "127.0.0.1";
    int port = 6379;
    const char *redis_password = "123456";

    redisContext *conn = redisConnect(host, port);
    if (conn->err)
    {
        printf("connection error:%s\n", conn->errstr);
        return -1;
    }

    reply = (redisReply *)redisCommand(conn, "AUTH %s", redis_password);
    if (reply->type == REDIS_REPLY_ERROR)
    {
        printf("password error!\n");
        return -1;
    }

    reply = redisCommand(conn, "set foo hellohiredis");
    freeReplyObject(reply);

    reply = redisCommand(conn, "get foo");

    printf("%s\n", reply->str);
    freeReplyObject(reply);

    redisFree(conn);

    return 0;
}

gcc hiredis_demo.c -o test -L/usr/local/lib -lhiredis

参考自:www.cnblogs.com/52fhy/p/919…