redis安装编译

redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库。

git clone https://gitee.com/mirrors/redis.git -b 6.2 
cd redis 
make && make install 

hredis安装编译

提供与redis通信(redis通信协议)的API的头文件,动态链接文件(.so)。安装后,头文件位于/usr/local/include/hiredis/。 动态库文件位于 /usr/local/lib/。

git clone https://github.com/redis/hiredis
make && make install

启动redis服务

cd redis
redis-server redis.conf

代码示例

test_redis.h

#ifndef _TEST_REDIS_T
#define _TEST_REDIS_T

#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;
	}
	
	bool connect(std::string host, int port) {
		this->_connect = redisConnect(host.c_str(), port);
		if(this->_connect != NULL && this->_connect->err) {
			printf("connect err: %s\n", this->_connect->errstr);
			return 0;
		}
		return 1;
	}

	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;
	} 

	void set(std::string key, std::string value) {
		redisCommand(this->_connect, "SET %s %s", key.c_str(), value.c_str());
	}

	//如果redis设置了密码,则需要密码登录
	void auth(std::string password){
		redisCommand(this->_connect, "auth %s", password.c_str());
	}

private:
		
	redisContext* _connect;
	redisReply* _reply;
};

#endif

test_redis.cpp

#include "test_redis.h"

int main()
{
	Redis *r = new Redis();
	if(!r->connect("127.0.0.1", 6379))
	{
		printf("connect error!\n");
		return 0;
	}
	r->auth("123456");
	r->set("name", "Andy");
	printf("Get the name is %s\n", r->get("name").c_str());
	delete r;
	return 0;
}

直接编译运行

编译

g++ test_redis.cpp -o test_redis -I/usr/local/include/  -L/usr/local/lib/ -lhiredis

运行

./test_redis

编写Makefile编译运行

vi Makefile
test_redis: test_redis.cpp test_redis.h
	g++ test_redis.cpp -o test_redis -I/usr/local/include/  -L/usr/local/lib/ -lhiredis

clean:
	rm test_redis.o test_redis

编译

make

运行

./test_redis
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐