【问题标题】:How to run Redis sadd commands with hiredis如何使用hiredis 运行Redis sadd 命令
【发布时间】:2022-01-08 09:22:24
【问题描述】:

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

这是一个redis中悲伤操作的演示。所有操作都失败,因为 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 members: WRONGTYPE 针对持有错误值的键的操作

【问题讨论】:

    标签: c++ database redis


    【解决方案1】:

    WRONGTYPE 对持有错误值的键的操作

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

    另外,你的代码有几个问题:

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

    由于你用的是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的作者。

    【讨论】:

    • 非常感谢!我在 github 上盯着你的项目。让我稍后试一试。
    猜你喜欢
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    相关资源
    最近更新 更多