这是一个示例代码,可以在.h头文件中定义Redis操作的类,包括连接、读取和写入等操作:

#ifndef REDIS_CLIENT_H
#define REDIS_CLIENT_H

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

using namespace std;

class RedisClient {
public:
    RedisClient(const string& host, int port) {
        m_redisCtx = redisConnect(host.c_str(), port);
    }

    ~RedisClient() {
        if (m_redisCtx) {
            redisFree(m_redisCtx);
        }
    }

    bool set(const string& key, const string& value) {
        redisReply* reply = (redisReply*)redisCommand(m_redisCtx, "SET %b %b", key.data(), key.size(), value.data(), value.size());
        bool ret = (reply != nullptr && reply->type == REDIS_REPLY_STATUS && strcasecmp(reply->str, "OK") == 0);
        freeReplyObject(reply);
        return ret;
    }

    bool get(const string& key, string& value) {
        redisReply* reply = (redisReply*)redisCommand(m_redisCtx, "GET %b", key.data(), key.size());
        bool ret = (reply != nullptr && reply->type == REDIS_REPLY_STRING);
        if (ret) {
            value.assign(reply->str, reply->len);
        }
        freeReplyObject(reply);
        return ret;
    }

private:
    redisContext* m_redisCtx;
};

#endif // REDIS_CLIENT_H

在.cpp文件中实现RedisClient类的具体操作:

#include "redis_client.h"

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

    string key = "test_key";
    string value = "test_value";

    if (redisClient.set(key, value)) {
        cout << "Set key: " << key << " value: " << value << " success" << endl;
    } else {
        cout << "Set key: " << key << " value: " << value << " failed" << endl;
    }

    string result;
    if (redisClient.get(key, result)) {
        cout << "Get key: " << key << " value: " << result << endl;
    } else {
        cout << "Get key: " << key << " failed" << endl;
    }

    return 0;
}
``
使用C++生成访问RedisI的代码把连接Redis和操作Redis写在h的头文件和cpp的文件里面

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

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