当前位置: 首页 > 工具软件 > RedisConnect > 使用案例 >

hiredis连接redis

卞坚成
2023-12-01

1.下载hiredis并且安装到库

git clone https://github.com/redis/hiredis
tar xzvf hiredis.tar.gz
make 
make install

2.网上抄一个测试代码,参考至(1条消息) c++操作redis数据库(详解)_@seven@的博客-CSDN博客_c++ redis

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.cpp

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

3.编译测试

g++ redis.cpp -lhiredis -o redis_test.test

./redis_test.test

//输出结果
Get the name is Mayuyu

4.错误解决

//运行时报错
./redis_test.test: error while loading shared libraries: libhiredis.so.1.1.1-dev: cannot open shared object file: No such file or directory

//解决方法

echo "/usr/local/lib" >> /etc/ld.so.conf.d/usr-libs.conf

/sbin/ldconfig

5.hiredis安装成功,可以开始愉快的学习了。

 类似资料: