使用C++生成访问RedisI的代码把连接Redis和操作Redis的方法分写在h的头文件和cpp的文件里面。。
以下是一个简单的示例,展示了如何使用C++连接Redis并执行一些简单的操作。
redis.h头文件:
#ifndef REDIS_H
#define REDIS_H
#include <hiredis/hiredis.h>
class Redis {
public:
Redis(const char* ip, int port);
~Redis();
bool connect();
bool set(const char* key, const char* value, int expire_time = 0);
char* get(const char* key);
bool del(const char* key);
private:
const char* ip_;
int port_;
redisContext* context_;
};
#endif // REDIS_H
redis.cpp源文件:
#include "redis.h"
#include <iostream>
Redis::Redis(const char* ip, int port) : ip_(ip), port_(port), context_(nullptr) {}
Redis::~Redis() {
if (context_ != nullptr) {
redisFree(context_);
}
}
bool Redis::connect() {
context_ = redisConnect(ip_, port_);
if (context_ == nullptr || context_->err) {
if (context_) {
std::cerr << "Error: " << context_->errstr << std::endl;
redisFree(context_);
} else {
std::cerr << "Can't allocate redis context" << std::endl;
}
return false;
}
return true;
}
bool Redis::set(const char* key, const char* value, int expire_time) {
redisReply* reply = static_cast<redisReply*>(
redisCommand(context_, "SET %s %s", key, value));
if (reply == nullptr || reply->type == REDIS_REPLY_ERROR) {
std::cerr << "Error: " << context_->errstr << std::endl;
freeReplyObject(reply);
return false;
}
if (expire_time != 0) {
redisReply* expire_reply = static_cast<redisReply*>(
redisCommand(context_, "EXPIRE %s %d", key, expire_time));
if (expire_reply == nullptr || expire_reply->type == REDIS_REPLY_ERROR) {
std::cerr << "Error: " << context_->errstr << std::endl;
freeReplyObject(expire_reply);
return false;
}
freeReplyObject(expire_reply);
}
freeReplyObject(reply);
return true;
}
char* Redis::get(const char* key) {
redisReply* reply = static_cast<redisReply*>(redisCommand(context_, "GET %s", key));
if (reply == nullptr || reply->type == REDIS_REPLY_ERROR) {
std::cerr << "Error: " << context_->errstr << std::endl;
freeReplyObject(reply);
return nullptr;
}
char* value = strdup(reply->str);
freeReplyObject(reply);
return value;
}
bool Redis::del(const char* key) {
redisReply* reply = static_cast<redisReply*>(redisCommand(context_, "DEL %s", key));
if (reply == nullptr || reply->type == REDIS_REPLY_ERROR) {
std::cerr << "Error: " << context_->errstr << std::endl;
freeReplyObject(reply);
return false;
}
freeReplyObject(reply);
return true;
}
使用示例:
#include "redis.h"
#include <iostream>
int main() {
Redis redis("127.0.0.1", 6379);
if (!redis.connect()) {
std::cerr << "Failed to connect to Redis" << std::endl;
return -1;
}
redis.set("foo", "bar");
char* value = redis.get("foo");
if (value != nullptr) {
std::cout << "Value of foo is: " << value << std::endl;
free(value);
} else {
std::cerr << "Failed to get value of foo" << std::endl;
}
redis.del("foo");
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/ef7x 著作权归作者所有。请勿转载和采集!