如何使用hiredis运行Redis-sad命令



我的代码包含一个头文件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: %sn", 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 %sn", r->set("names", "Andy").c_str());
printf("Sadd names Andy %sn", r->set("names", "Andy").c_str());
printf("Sadd names Alice %sn", r->set("names", "Alice").c_str());
printf("names members: %sn", r->output("names").c_str());
delete r;
return 0;
}

结果:

Sadd命名Andy WRONGTYPE针对持有错误类型值的密钥进行操作

Sadd命名Andy WRONGTYPE针对持有错误类型值的密钥进行操作

Sadd将Alice WRONGTYPE操作命名为针对持有错误类型值的密钥

names成员:针对持有错误类型值的密钥的WRONGTYPE操作

WRONGTYPE针对持有错误类型值的密钥的操作

这意味着密钥,即名称,已经设置,并且其类型不是set。您可以使用redis-cli运行TYPE names来查看密钥的类型。

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

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

由于您使用的是C++,您可以尝试基于hiredis的redis-plus-plus,并具有更友好的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的作者。

最新更新