配置 Redis

一.Windows 环境下安装 MySQL

在 Windows 环境下安装 Redis 主要是借助 Visual Studio 的 MSVC 工具集进行开发。后续当然还是将工程迁移到 Linux 系统上最好。

下载安装包

编译安装

二.Linux 环境下安装 Redis

2.1 安装服务端和客户端

Linux的 Redis 库直接编译安装即可。ArchLinux 系统中安装 Redis 即可。

  1. 首先安装 redis 服务端库:

    1
    sudo pacman -S redis
  2. 然后启动服务并设置为开机自启

    1
    2
    3
    4
    # 立即启动服务
    sudo systemctl start redis
    # 设置开机自启动
    sudo systemctl enable redis
  3. 安装 hiredis 客户端库:

    1
    sudo pacman -S hiredis

2.2 测试与编译

测试代码

  1. 首先编写一段简单的测试代码,在合适的位置创建一个 test_redis.cpp 文件

    1
    2
    3
    4
    # 创建测试文件
    sudo touch test_redis.cpp
    # 打开并编辑测试文件
    sudo vim test_redis.cpp
  2. 然后将下面代码粘贴进去:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    #include <iostream>
    #include <hiredis/hiredis.h>

    int main() {
    // 连接Redis服务器
    redisContext *c = redisConnect("127.0.0.1", 6379);
    if (c == NULL || c->err) {
    if (c) {
    std::cerr << "连接错误: " << c->errstr << std::endl;
    } else {
    std::cerr << "无法分配redisContext。" << std::endl;
    }
    return 1;
    }
    std::cout << "成功连接到Redis服务器" << std::endl;

    // 执行SET命令
    redisReply *reply = (redisReply *)redisCommand(c, "SET %s %s", "my_key", "Hello from C++!");
    if (reply == NULL) {
    std::cerr << "执行SET命令失败。" << std::endl;
    redisFree(c);
    return 1;
    }
    freeReplyObject(reply);

    // 执行GET命令
    reply = (redisReply *)redisCommand(c, "GET %s", "my_key");
    if (reply == NULL) {
    std::cerr << "执行GET命令失败。" << std::endl;
    redisFree(c);
    return 1;
    }
    std::cout << "获取到的值: " << reply->str << std::endl;
    freeReplyObject(reply);

    // 断开连接
    redisFree(c);
    return 0;
    }
  3. 最后保存退出。

编译运行

在终端中编译并运行此测试示例:

1
2
3
4
# 编译
g++ -o test_redis test_redis.cpp -lhiredis
# 运行
./test_redis

示例结果如下所示:

1
2
成功连接到Redis服务器 
获取到的值: Hello from C++!

2.3 更多配置

将远程连接,持久化,认证密码等配置写入配置文件。在 /etc/redis.conf 中即可配置相关项

1
2
3
4
5
6
7
8
9
10
# 1.远程连接,允许远程连接
bind 0.0.0.0
# 开启保护模式,默认是yes(限制为本地访问),【这样做会降低安全性,请确保你的防火墙已正确配置】
protected-mode no

# 2.持久化,开启之后Redis不会每次重启自动清空
appendonly yes

# 3.认证密码,为Redis设置访问密码
requirepass ~K^S0Y^E+ijGkp_^

三.Docker 环境下安装 Redis

将 Redis 部署到 Docker 环境中可以有效隔绝外部攻击,通过设置不同策略实现安全访问 Redis 服务。笔者在云服务器 Linux 系统上部署 Docker 环境,并在 Docker 环境中部署 Redis 实现远程访问 Redis 服务。

具体安装流程可以参看 [[Docker 配置 Redis 和 MySQL]]