#include <hiredis/hiredis.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
const char* pwd = "redis";
redisContext* ctx;
redisReply* reply;
ctx = redisConnect("127.0.0.1", 6379);
if (ctx->err) {
printf("Connection error:%s\n", ctx->errstr);
redisFree(ctx);
}
reply = (redisReply*)redisCommand(ctx, "auth %s", pwd);
if (NULL == reply) {
printf("Execut cmd failure\n");
redisFree(ctx);
}
string hval = "{\"name\":\"xiaoming\"}";
reply = (redisReply*)redisCommand(ctx, "hset small_ship 9987777 %s", hval);
cout << reply << endl;
freeReplyObject(reply);
return 0;
}
结果发现写入的Value变成乱码了:
把代码稍作修改
原来的代码:
reply = (redisReply*)redisCommand(ctx, "hset small_ship 9987777 %s", hval);
修改成:
reply = (redisReply*)redisCommand(ctx, "hset small_ship 9987777 %s", hval.c_str());
恢复正常