配置 Redis

配置 Redis
DustWind一.Windows 环境下安装 MySQL
在 Windows 环境下安装 Redis 主要是借助 Visual Studio 的 MSVC 工具集进行开发。后续当然还是将工程迁移到 Linux 系统上最好。
下载安装包
编译安装
二.Linux 环境下安装 Redis
2.1 安装服务端和客户端
Linux的 Redis 库直接编译安装即可。ArchLinux 系统中安装 Redis 即可。
首先安装
redis服务端库:1
sudo pacman -S redis
然后启动服务并设置为开机自启
1
2
3
4立即启动服务
sudo systemctl start redis
设置开机自启动
sudo systemctl enable redis安装
hiredis客户端库:1
sudo pacman -S hiredis
2.2 测试与编译
测试代码
首先编写一段简单的测试代码,在合适的位置创建一个
test_redis.cpp文件1
2
3
4创建测试文件
sudo touch test_redis.cpp
打开并编辑测试文件
sudo vim test_redis.cpp然后将下面代码粘贴进去:
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
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;
}最后保存退出。
编译运行
在终端中编译并运行此测试示例:
1 | 编译 |
示例结果如下所示:
1 | 成功连接到Redis服务器 |
2.3 更多配置
将远程连接,持久化,认证密码等配置写入配置文件。在 /etc/redis.conf 中即可配置相关项
1 | # 1.远程连接,允许远程连接 |
三.Docker 环境下安装 Redis
将 Redis 部署到 Docker 环境中可以有效隔绝外部攻击,通过设置不同策略实现安全访问 Redis 服务。笔者在云服务器 Linux 系统上部署 Docker 环境,并在 Docker 环境中部署 Redis 实现远程访问 Redis 服务。
具体安装流程可以参看 [[Docker 配置 Redis 和 MySQL]]
评论
匿名评论隐私政策
✅ 你无需删除空行,直接评论以获取最佳展示效果









