ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 3.9 redis-C++-API Redis官方引入的c++库众多,但官方没有重点推荐使用哪个: http://redis.cn/clients.html#c-- 除此之外可以使用Redis官方提供的C语言实现的客户端hiredis,进行封装定制 ```cpp //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; } 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; } 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 ``` ```cpp //main.cpp #include "redis.h" int main(void) { Redis *r = new Redis(); if(!r->connect("127.0.0.1", 6379)) { printf("connect error!\n"); return 0; } r->set("name", "itcast cpp"); printf("Get the name is %s\n", r->get("name").c_str()); delete r; return 0; } ``` 编译: ```bash g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis ```