linux版本的资料比windows多很多。操作也相对比较容易
以centos7为例,安装和编译redis。
1.安装redis
官网给出了安装方式
$ wget https://download.redis.io/releases/redis-6.2.4.tar.gz
$ tar xzf redis-6.2.4.tar.gz
$ cd redis-6.2.4
$ make
$ make install
然后启动即可
$ redis-server
注意,需要安装一个tcl,redis的一个依赖
$ yum install tcl
如果需要修改配置,可以
2.安装hiredis(redis的c++客户端)
$ wget https://github.com/redis/hiredis/archive/v0.14.0.tar.gz
$ tar -xzf v0.14.0.tar.gz
$ make
$ make install
3.自己写的redis客户端,网上很多例子,随便那一个,主要是环境需要跑成功。如果项目上使用再另行封装,暂时只需要跑起来
3.1编辑main.cpp
#include
#include
#include
#include
#include
#include
#include
void doTest()
{
//redis默认监听端口为6387 可以再配置文件中修改
redisContext* c = redisConnect("127.0.0.1", 6379);
if ( c->err)
{
redisFree(c);
printf("Connect to redisServer faile\n");
return ;
}
printf("Connect to redisServer Success\n");
const char* command1 = "set stest1 value1";
redisReply* r = (redisReply*)redisCommand(c, command1);
if( NULL == r)
{
printf("Execut command1 failure\n");
redisFree(c);
return;
}
if( !(r->type == REDIS_REPLY_STATUS && strcasecmp(r->str,"OK")==0))
{
printf("Failed to execute command[%s]\n",command1);
freeReplyObject(r);
redisFree(c);
return;
}
freeReplyObject(r);
printf("Succeed to execute command[%s]\n", command1);
const char* command2 = "strlen stest1";
r = (redisReply*)redisCommand(c, command2);
if ( r->type != REDIS_REPLY_INTEGER)
{
printf("Failed to execute command[%s]\n",command2);
freeReplyObject(r);
redisFree(c);
return;
}
int length = r->integer;
freeReplyObject(r);
printf("The length of 'stest1' is %d.\n", length);
printf("Succeed to execute command[%s]\n", command2);
const char* command3 = "get stest1";
r = (redisReply*)redisCommand(c, command3);
if ( r->type != REDIS_REPLY_STRING)
{
printf("Failed to execute command[%s]\n",command3);
freeReplyObject(r);
redisFree(c);
return;
}
printf("The value of 'stest1' is %s\n", r->str);
freeReplyObject(r);
printf("Succeed to execute command[%s]\n", command3);
const char* command4 = "get stest2";
r = (redisReply*)redisCommand(c, command4);
if ( r->type != REDIS_REPLY_NIL)
{
printf("Failed to execute command[%s]\n",command4);
freeReplyObject(r);
redisFree(c);
return;
}
freeReplyObject(r);
printf("Succeed to execute command[%s]\n", command4);
redisFree(c);
}
int main()
{
doTest();
return 0;
}
3.2编译
g++ -lhiredis -o main main.cpp
3.3运行
./main
报错,
$ mkdir /usr/lib/hiredis
$ cp libhiredis.so /usr/lib/hiredis #将动态连接库libhiredis.so至/usr/lib/hiredis
$ mkdir /usr/include/hiredis
$ cp hiredis.h /usr/include/hiredis
$ echo '/usr/local/lib' >>/etc/ld.so.conf
$ ldconfig
然后再运行即可