以下是一个使用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方法获取了该键值对的值。最后,我们输出了获取的值

使用C++生成访问RedisI的代码把连接Redis和操作Redis写在不同的方法内相互调用。

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

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