以下是一个使用 C++ 生成访问 Redis 的代码示例,将连接 Redis 和操作 Redis 分别封装在不同的方法中:

#include <iostream>
#include <string>
#include <hiredis/hiredis.h>

class RedisClient {
private:
    redisContext *context;

public:
    RedisClient(std::string host, int port) {
        // 创建 Redis 连接
        context = redisConnect(host.c_str(), port);
        if (context == NULL || context->err) {
            if (context) {
                std::cout << "Error: " << context->errstr << std::endl;
                redisFree(context);
            } else {
                std::cout << "Error: Failed to allocate redis context" << std::endl;
            }
            exit(1);
        }
    }

    ~RedisClient() {
        // 释放 Redis 连接
        redisFree(context);
    }

    std::string get(std::string key) {
        // 获取 Redis 数据
        redisReply *reply = (redisReply *)redisCommand(context, "GET %s", key.c_str());
        if (reply == NULL) {
            std::cout << "Error: Failed to get redis data" << std::endl;
            return "";
        } else if (reply->type == REDIS_REPLY_NIL) {
            std::cout << "Error: Redis data not found" << std::endl;
            freeReplyObject(reply);
            return "";
        } else if (reply->type != REDIS_REPLY_STRING) {
            std::cout << "Error: Redis data type not supported" << std::endl;
            freeReplyObject(reply);
            return "";
        } else {
            std::string value(reply->str, reply->len);
            freeReplyObject(reply);
            return value;
        }
    }

    void set(std::string key, std::string value) {
        // 设置 Redis 数据
        redisReply *reply = (redisReply *)redisCommand(context, "SET %s %s", key.c_str(), value.c_str());
        if (reply == NULL) {
            std::cout << "Error: Failed to set redis data" << std::endl;
        } else if (reply->type == REDIS_REPLY_ERROR) {
            std::cout << "Error: Failed to set redis data: " << reply->str << std::endl;
            freeReplyObject(reply);
        } else {
            freeReplyObject(reply);
        }
    }
};

int main() {
    RedisClient client("localhost", 6379);

    // 设置 Redis 数据
    client.set("name", "Alice");
    std::cout << "Set name to " << client.get("name") << std::endl;

    // 获取 Redis 数据
    std::cout << "Get name: " << client.get("name") << std::endl;

    return 0;
}

在这个示例中,我们定义了一个名为RedisClient的类,该类包含了连接 Redis 和操作 Redis 的方法。在类的构造函数中,我们使用redisConnect函数创建了一个 Redis 连接,并检查了连接是否成功。在类的析构函数中,我们使用redisFree函数释放了 Redis 连接。

get方法用于获取 Redis 数据,首先使用redisCommand函数发送一个GET命令,然后检查返回值并返回结果。如果返回值为NULL,则表示获取数据失败;如果返回值的类型为REDIS_REPLY_NIL,则表示数据不存在;如果返回值的类型不是REDIS_REPLY_STRING,则表示数据类型不受支持;否则,我们将结果转换为字符串并返回。

set方法用于设置 Redis 数据,首先使用redisCommand函数发送一个SET命令,然后检查返回值并释放返回值对象。

在main函数中,我们创建了一个RedisClient对象,然后使用set方法设置了一个名为name的 Redis 键值对,并使用get方法获取了该键值对的值。最后,我们输出了获取的值。

通过将连接和操作 Redis 分别封装在不同的方法中,我们可以使代码结构更加清晰,提高代码的可读性和可维护性。

C++ 连接 Redis 示例:分离连接和操作方法

原文地址: https://www.cveoy.top/t/topic/nPBO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录