配置说明:
Redis 服务端安装在ubuntu上
客户端通过C++远程访问Redis服务
ubuntu上安装方法:
//在终端中安装Redis服务器端
sudo apt-get install redis-server
安装完成后,Redis服务器会自动启动,我们检查Redis服务器程序
可以看到:
- 1
- 2
- 1
- 2
显示: tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN
- 1
- 2
- 1
- 2
显示: redis-server is running
Redis的配置
默认服务端只开启了本地回路访问127.0.0.1,想要远程访问,必须修改绑定地址为外网ip
1、 使用Redis的访问账号
默认情况下,访问Redis服务器是不需要密码的,为了增加安全性我们需要设置Redis服务器的访问密码。设置访问密码为redis。
用vi打开Redis服务器的配置文件redis.conf
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
2、 让Redis服务器被远程访问
默认情况下,Redis服务器不允许远程访问,只允许本机访问,所以我们需要设置打开远程访问的功能。
用vi打开Redis服务器的配置文件redis.conf
修改完以上配置,重启该redis服务即可让设置生效。重启命令:
service redis-server restart
windows平台远程访问该redis数据服务端代码如下:
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 aaa 12345";
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);
}