如何 运行 Redis 使用 hiredis 添加命令

How to run Redis sadd commands with hiredis

我的代码包含一个头文件 redis.h 和一个 c++ 源文件 redis.cpp。

这是redis中sadd操作的demo。所有操作都失败,因为 WRONGTYPE 操作针对持有错误类型值的键。我不知道发生了什么。

请给我一些建议。

//redis.h
#ifndef _REDIS_H_
#define _REDIS_H_

#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>

#include <hiredis/hiredis.h>

using namespace std;

class Redis{
public:
    Redis(){}
    ~Redis(){
        this->_connect =NULL;
        this->_reply=NULL;
    }

    bool connect(string host, int port){
        this->_connect = redisConnect(host.c_str(), port);
        if(this->_connect != NULL && this->_connect->err){
            printf("connect error: %s\n", this->_connect->errstr);
            return 0;
        }
        return 1;
    }

    string set(string key, string value){
        this->_reply = (redisReply*)redisCommand(this->_connect, "sadd %s %s", key.c_str(), value.c_str());
        string str = this->_reply->str;
        return str;
    }

    string output(string key){
        this->_reply = (redisReply*)redisCommand(this->_connect, "smembers %s", key.c_str());
        string str = this->_reply->str;
        freeReplyObject(this->_reply);
        return str;
    }

private:
    redisContext * _connect;
    redisReply* _reply;
};

#endif //_REDIS_H

//redis.cpp
#include "redis.h"

int main(){
    Redis *r = new Redis();
    if(!r->connect("127.0.0.1", 6379)){
        printf("connect error!\n");
        return 0;
    }
    printf("Sadd names Andy %s\n", r->set("names", "Andy").c_str());
    printf("Sadd names Andy %s\n", r->set("names", "Andy").c_str());
    printf("Sadd names Alice %s\n", r->set("names", "Alice").c_str());
    printf("names members: %s\n", r->output("names").c_str());
    delete r;
    return 0;
}

结果:

Sadd names Andy WRONGTYPE 针对包含错误类型值的键的操作

Sadd names Andy WRONGTYPE 针对包含错误类型值的键的操作

Sadd names Alice WRONGTYPE 针对包含错误类型值的键的操作

names 成员:WRONGTYPE 对包含错误类型值的键的操作

WRONGTYPE Operation against a key holding the wrong kind of value

这意味着键,即 names,已经被设置,并且它的类型不是 SET。你可以 运行 TYPE names 使用 redis-cli 查看密钥的类型。

此外,您的代码有几个问题:

  • redisConnect 可能 return 空指针
  • 您没有在 set 方法中调用 redisFree 来释放 redisReply 的资源
  • saddsmembers 不 return 字符串回复,所以你无法得到正确的回复

既然你用的是C++,你可以试试redis-plus-plus,它基于hiredis,有更C++友好的界面:

try {
    auto r = sw::redis::Redis("tcp://127.0.0.1:6379");
    r.sadd("names", "Andy");
    r.sadd("names", "Alice");
    std::vector<std::string> members;
    r.smembers("names", std::back_inserter(members));
} catch (const sw::redis::Error &e) {
    // error handle
}

免责声明:我是 redis-plus-plus 的作者。