我的代碼包含一個頭檔案 redis.h 和一個 C 源檔案 redis.cpp。
這是redis中sadd opeion的演示。所有操作都失敗了,因為對持有錯誤型別值的鍵的 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;
}
結果:
悲傷的名字 Andy WRONGTYPE 針對持有錯誤型別值的鍵的操作
悲傷的名字 Andy WRONGTYPE 針對持有錯誤型別值的鍵的操作
悲傷的名字 Alice WRONGTYPE 對持有錯誤型別值的鍵進行操作
名稱成員:WRONGTYPE 對持有錯誤型別值的鍵的操作
uj5u.com熱心網友回復:
WRONGTYPE 對持有錯誤型別值的鍵進行操作
這意味著鍵,即names,已經被設定,并且它的型別不是 SET。可以TYPE names用redis-cli運行查看key的型別。
此外,您的代碼有幾個問題:
redisConnect可能回傳空指標- 你不叫
redisFree釋放的資源redisReply在你的set方法 sadd并且smembers不回傳字串回復,因此您無法獲得正確回復
既然你用的是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 的作者。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372325.html
上一篇:無法連接到雪花資料庫[PHP]
下一篇:表格單元格中的多個專案
