C++接入redis

发布时间 2023-10-16 21:54:44作者: 黄河大道东

项目地址

https://github.com/sewenew/redis-plus-plus

https://github.com/redis/hiredis

# 1、编译安装 hiredis 项目
wget https://github.com/redis/hiredis/archive/refs/tags/v1.2.0.tar.gz
cd hiredis
# 编译安装
make && make PREFIX=安装到指定目录 install

# 2、编译安装 redis-plus-plus 项目
wget https://github.com/sewenew/redis-plus-plus/archive/refs/tags/1.3.10.tar.gz
cd redis-plus-plus && mkdir build && cd build
cmake -DCMAKE_PREFIX_PATH=hiredis的安装目录 -DCMAKE_INSTALL_PREFIX=redis-plus-plus的安装目录 ..
make && make install

使用

#include <iostream>
#include "sw/redis++/redis++.h"
using namespace sw::redis;

int main(int argc, char const *argv[]) {
    ConnectionOptions option{};
    option.host = "xxx.108.254.101";
    option.port = 6379;
    option.password = "jtzlredis";
    Redis redis = Redis(option);
    std::cout <<  redis.ping() << std::endl;
    // 其它命令
    return 0;
}

特别的编译选项

  • -lredis++
  • -lhiredis
  • -std=c++17
  • -lpthread
  • -Wall