Redis配置环境及Linux下C++连接Redis
配置了一晚上,总算将Linux(Ubuntu18.04)下的C++连接上了Redis。
先说结论,Linux C++连接Redis分为三步:
1.Linux下载Redis服务器端,并且开启服务端
2.Linux下载hiredis,hiredis作为C++与redis连接的接口
3.编写本地代码,连接redis服务器端
1.Linux下载Redis服务器端,并且开启服务端
第一步这位大佬已经写的非常详细了,下列网址可供参考
Redis基础环境配置
我感觉做下来首先就是将运行的基础环境搭建好了,并且进行了分目录,这样比如找一个Redis相应的配置文件redis.conf也非常的方便(这里放的地方是/usr/local/redis/etc)。而一些关键的可执行文件则放到了/etc/local/redis/bin下面。下面的第一条命令一定要执行,如果想直接在服务器本地执行客户端可执行下面第二三条命令。
//开启服务端
//执行目录为/usr/local/redis/bin
./redis-server /usr/local/redis/etc/redis.conf
//开启客户端
//执行目录为/usr/local/redis/bin
./redis-cli
//显示错误:NOAUTH Authentication required.
//原因:没有输入密码,没有权限执行命令,执行下列命令
auth [密码]
2.Linux下载hiredis,hiredis作为C++与redis连接的接口
//下载hiredis,任意目录即可
wget https://github.com/redis/hiredis
cd hiredis
make
make install
sudo /sbin/ldconfig
3.编写本地代码,连接redis服务器端
创建文件夹并编写相关代码文件
mkdir test
cd test
touch redis.h redis.cpp
//redis.h
#ifndef _REDIS_H_
#define _REDIS_H_
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <hiredis/hiredis.h>
class Redis
{
public:
Redis(){
}
//释放资源
~Redis(){
this->_connect = NULL;
this->_reply = NULL;
this->authreply = NULL;
}
//创建连接
bool connect(std::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;
}else{
printf("Redis连接成功!\n");
}
redisReply *authreply = (redisReply *)redisCommand(this->_connect, "auth %s", redis_password);
if (authreply->type == REDIS_REPLY_ERROR){
printf("Redis认证失败!\n");
}else{
printf("Redis认证成功!\n");
}
return 1;
}
//get请求
std::string get(std::string key){
this->_reply = (redisReply*)redisCommand(this->_connect, "GET %s", key.c_str());
std::string str = this->_reply->str;
freeReplyObject(this->_reply);
return str;
}
//set请求
void set(std::string key, std::string value){
redisCommand(this->_connect, "SET %s %s", key.c_str(), value.c_str());
}
private:
redisContext* _connect;
redisReply* _reply;
redisReply* authreply;
char redis_password[7] = {
'1','2','3','4','5','6','\0'};
};
#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;
}
r->set("name", "nietengtao");
printf("Get the name is %s\n", r->get("name").c_str());
delete r;
return 0;
}
编译命令:
sudo g++ redis.cpp -o redisntt -L /usr/local/redis -lhiredis
4.中途出现的错误
1.NOAUTH Authentication required.
编译后出现的错误,由于没有权限导致的,在redis.h加入了redisCommand执行相关密码认证就可以了。这里我用的密码是123456,如果在配置文件redis.conf设置无密码应该就不用此认证了。
2.找不到动态链接库
具体错误名忘了,可以通过修改/etc/ld.so.conf来添加动态链接库的位置,这里我使用的是
echo "/usr/lcoal/lib" >> /etc/ld.so.conf
3.找不到redis服务端
它当时报的错是非常多的,说明只执行了二三步,还没执行第一步~