1.安装hiredis.h接口

C++来操作redis数据库,是通过hiredis.h接口来实现,目前只能在Linux环境使用。

git clone https://github.com/redis/hiredis

tar -zxvf hiredis.tar.gz
ls
make 
 #接下来把libhiredis.so放到/usr/local/lib/中,把hiredis.h放到/usr/local/inlcude/hiredis/中或者直接用命令make install配置 两个都可以
make install

到此已经安装成功,接下来在程序中就可以直接用了,在程序中包含#include <hiredis/hiredis.h>即可

2.redis接口

2.1.连接数据库

redisContext* redisConnect(const char *ip, int port);

  该函数用来连接redis数据库, 两个参数分别是redis数据库的ip和端口,端口号一般为6379,返回值是操作数据库的句柄。类似的还提供了一个函数,供连接超时限定,即

redisContext* redisConnectWithTimeout(const char *ip, int port, timeval tv)。

2.2释放数据库连接

void redisFree(redisContext *c)

释放redisConnect()所产生的连接。

2.3.操作数据库

void *redisCommand(redisContext *c, const char *format...)

  该函数用于执行redis数据库中的命令,第一个参数为连接数据库返回的redisContext,剩下的参数为变参,如同C语言中的prinf()函数。此函数的返回值为void*,是返回命令的结果,但是一般会强制转换为redisReply类型,以便做进一步的处理。

void freeReplyObject(void *reply);

 释放redisCommand执行后返回的的redisReply所占用的内存

3.案例

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;	    	    
	}
 //创建连接
	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;
		}
		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;
				
};
 
#endif  //_REDIS_H_

redis.cppt源文件

#include "redis.h"
 
int main()
{
	Redis *r = new Redis();
	if(!r->connect("192.168.13.128", 6379))
	{
		printf("connect error!\n");
		return 0;
	}
	r->set("name", "Mayuyu");
	printf("Get the name is %s\n", r->get("name").c_str());
	delete r;
	return 0;
}

Logo

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

更多推荐