hiredis中使用空格

cli中使用sadd key data1 data2的时候,查询到的是两个数据,有时候我们需要data1和data2为一个数据,比如 sadd key  "hello world",在命令中使用双引号将hello world包起来即可。

hiredis下可用如下方式:

1. 使用redisCommand

redisCommand(ctx, "SADD %s %s", key.c_str(), "hello world  131231");

2. 使用redisCommandArgv

#include 
#include "hiredis/hiredis.h"
#include 


int main() 
{
    redisContext *ctx = redisConnect("127.0.0.1", 6379);
    if (ctx->err) 
    {
        printf("connection fail\n");
        redisFree(ctx);
        return -1;
    }

    std::string a("SET");
    std::string b("foo");
    std::string c("12345");

    std::vector s_vec;
    s_vec.push_back(a.c_str());
    s_vec.push_back(b.c_str());
    s_vec.push_back(c.c_str());

    redisReply *reply = (redisReply *)redisCommandArgv(ctx, s_vec.size(), &(s_vec[0]), NULL);
    freeReplyObject(reply);

    reply = (redisReply *)redisCommand(ctx, "GET foo");
    printf("GET foo: %s\n", reply->str);
    freeReplyObject(reply);

    std::string cmd("SADD");
    std::string key("key");
    std::string context("hello world");

    std::vector argv;
    std::vector arg_len;
    argv.reserve(10);
    arg_len.reserve(10);

    argv.emplace_back(cmd.c_str());
    argv.emplace_back(key.c_str());
    argv.emplace_back(context.c_str());
    arg_len.emplace_back(cmd.size());
    arg_len.emplace_back(key.size());
    arg_len.emplace_back(context.size());

    reply = (redisReply *)redisCommandArgv(ctx, argv.size(), &(argv[0]), NULL);
    if(NULL == reply)
    {
        printf("%s fail.\n", "SADD");
        return -1;
    }

    if (reply->type == REDIS_REPLY_ERROR) 
    {
        printf("%s reply fail\n", reply->str);
        return -1;
    }

    if(reply->integer == 1)
    {
        printf("success\n");
    }

    freeReplyObject(reply);


    std::string get_cmd = "SMEMBERS " + key;
    printf("Get CMD = %s\n", get_cmd.c_str());
    reply = (redisReply *)redisCommand(ctx, get_cmd.c_str());
    if(NULL == reply)
    {
        printf("%s fail.\n", cmd);
        return -1;
    }


    if(reply->type != REDIS_REPLY_ARRAY)
    {
      printf("%s reply fail\n", get_cmd.c_str());
      freeReplyObject(reply);
      return -1;
    }

    int elements_cnt = reply->elements;
    printf("SMEMBERS watch elements cnt is %d\n", elements_cnt);
    printf("SMEMBERS watch\n");
    for(int i = 0; i < elements_cnt; i++)
    {
        printf("%s\n", reply->element[i]->str);
    }

    freeReplyObject(reply);
    redisFree(ctx);

    return 0;
}

你可能感兴趣的:(java,c++,开发语言)