c++操作redis数据库(详解)

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

  • 6
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值