当前位置: 首页 > 工具软件 > RedisConnect > 使用案例 >

C++连接redis示例

贺俊材
2023-12-01

我们通过第三方库hiredis来连接redis。

hiredis.h 的下载地址为: https://github.com/redis/hiredis

1、下载安装hiredis库:

$ wget https://github.com/redis/hiredis/archive/master.zip
$ mv hiredis-master /usr/loca
$ cd /usr/local

#解压、编译
$ unzip hiredis-master
$ cd hiredis-master
$ make
$ sudo make install
mkdir -p /usr/local/include/hiredis /usr/local/include/hiredis/adapters /usr/local/lib
cp -pPR hiredis.h async.h read.h sds.h sslio.h /usr/local/include/hiredis
cp -pPR adapters/*.h /usr/local/include/hiredis/adapters
cp -pPR libhiredis.so /usr/local/lib/libhiredis.so.0.14
cd /usr/local/lib && ln -sf libhiredis.so.0.14 libhiredis.so
cp -pPR libhiredis.a /usr/local/lib
mkdir -p /usr/local/lib/pkgconfig
cp -pPR hiredis.pc /usr/local/lib/pkgconfig

安装后,会把库文件、头文件拷贝到系统默认的/usr/local/lib和/usr/local/include中,这样,我们在写C++代码时,就可以直接引入、编译连接了。

2、源代码:1)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  //_REDIS_H_

2)redis.cpp

#include "redis.h"

int main()
{
  Redis *r = new Redis();
  if(!r->connect("192.168.13.128", 6379))
  {
    printf("connect error!\n");
    return 0;
  }
  r->set("name", "Mayuyu");
  printf("Get the name is %s\n", r->get("name").c_str());
  delete r;
  return 0;
}

3)编译链接:

g++ -o run redis.cpp -lhiredis

4)运行:

ldconfig

./run

 

 类似资料: