【发布时间】: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 针对持有错误值的键的操作
【问题讨论】: