C++ Redis mset 二进制数据接口封装方案
  需求
  C++中使用hiredis客户端接口访问redis;
  需要使用mset一次设置多个二进制数据
  以下给出三种封装实现方案;
  简单拼接方案
  在redis-cli中,mset的语法是这样的:
  /opt/colin$./redis-cli mset a 11 b 22 c 333
  OK
  按照这样的语法拼接后,直接使用hiredis字符串接口redisCommand传递:
void msetNotBinary(redisContext *c, const vector<string> &vtKey, const vector<string> & vtVal )
{
if(vtKey.size() != vtVal.size())
{
throw runtime_error( "Redis error" );
}
string strCmd = "MSET";
for(int i = 0; i < vtKey.size(); i++)
{
strCmd += " "+vtKey[i]+" "+vtVal[i];
}
cout << "strCmd:" << strCmd << endl;
void * r =  redisCommand(c, strCmd.c_str() );
if ( !r )
throw runtime_error( "Redis error" );
freeReplyObject( r );
}
void do_test( redisContext *c )
{
vector<string> vtKey;
vector<string> vtVal;
vtKey.push_back("A");
vtVal.push_back("AAAA");
vtKey.push_back("B");
vtVal.push_back("BBBB");
vtKey.push_back("C");
vtVal.push_back("CCCC");
//add a binary data
vtKey.push_back("D");
vtVal.push_back("");
char a[] = "ABCDE";
a[2] = 0;
vtVal[3].assign(a,5);
try
{
msetNotBinary(c, vtKey, vtVal );
//mset1( c, vtKey, vtVal );
//mset2( c, vtKey, vtVal );
}
catch ( runtime_error & )
{
cout << "Error" << endl;
}
}
int main(int argc, char *argv[])
{
redisContext *c;
c = redisConnect("127.0.0.1",6379);
if (c->err)
{
cout << "Connection error: " << c->errstr << endl;
return -1;
}
do_test(c);
redisFree(c);
return 0;
}