• c连接redis


    1. 安装启动redis

    2. 安装redis c语言客户端

    #include <stdio.h>
    #include <stdlib.h>
    #include <hiredis.h>
    
    int main(int argc, char **argv) {
    //    if (argc < 3) {
    //        printf("usage: connRedis hostname port password
    ");
    //        return 1;
    //    }
    //    char *hostname = argv[1];
    //    int port = atoi(argv[2]);
    //    char *password = argv[3];
    
        char *hostname = "127.0.0.1";
        int port = 6379;
        char *password = "";
    
        redisContext *conn;
        redisReply *reply;
        struct timeval timeout = {1, 500000};
        conn = redisConnectWithTimeout(hostname, port, timeout);
        // conn erro
        if (conn == NULL || conn->err) {
            if (conn) {
                printf("connection error %s
    ", conn->errstr);
                exit(1);
            } else {
                printf("cannot alloc redis context
    ");
                exit(1);
            }
        }
    
        // auth
        reply = redisCommand(conn, "AUTH %s", password);
        printf("auth is %s
    ", reply->str);
        freeReplyObject(reply);
    
        // set
        reply = redisCommand(conn, "set %s %s", "name", "hello world");
        printf("set is %s
    ", reply->str);
        freeReplyObject(reply);
    
        // get
        reply = redisCommand(conn, "get name");
        printf("name :%s
    ", reply->str);
        freeReplyObject(reply);
    
        // free conn
        redisFree(conn);
        return 0;
    }

    编译: gcc connRedis.c -o connRedis  -I /usr/local/include/hiredis -lhiredis

    这里用clion + cmake编译,运行。需要在CMakeList.txt中添加动态库hiredis

    link_libraries(hiredis)
    add_executable(connRedis.c connRedis)
    

     注意,link要放前面

  • 相关阅读:
    C/C++笔试题
    #include "" 和 #include <> 的区别
    cc、gcc、g++、CC的区别概括
    在shell脚本中调用另一个脚本的三种不同方法(fork, exec, source)
    vi复制粘贴
    cleartool常用命令
    [转]Tomcat日志详解
    Profile
    Bean的初始化和销毁
    SpringEL和资源调用
  • 原文地址:https://www.cnblogs.com/luckygxf/p/12259877.html
Copyright © 2020-2023  润新知