Ubuntu安装redis

第一步:安装 Redis

# 1. 更新软件包列表
sudo apt update

# 2. 安装Redis
sudo apt install redis-server -y

# 3. 检查Redis版本
redis-server --version

# 4. 查看服务状态
sudo systemctl status redis-server

如果系统显示 active (running),说明 Redis 服务已经自动启动了。

第二步:安全与性能配置(关键步骤)

备份原配置文件

sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.bak

编辑配置文件

sudo nano /etc/redis/redis.conf

修改关键参数

设置密码(requirepass):找到 # requirepass foobared 行,取消注释并将 foobared 替换为一个强密码。

requirepass 你的强密码
(请务必将 你的强密码 替换成你自己的,并记下来,后面会用)

绑定本地地址(bind):确保 Redis 不会对外网暴露,只允许本机访问来保证安全。确认以下 bind 行是唯一的:

bind 127.0.0.1

设置内存限制(maxmemory):防止 Redis 内存无限增长直至系统崩溃。你的服务器是2核2G的,建议设置约 1GB(约 70%)。

maxmemory 1024mb

设置内存策略(maxmemory-policy): 当内存到达上限时,允许 Redis 自动删除旧数据。

maxmemory-policy allkeys-lru

推荐修改:守护模式(daemonize):yes 确保 Redis 作为守护进程在后台运行。

daemonize yes

重启 Redis 服务

# 检查配置文件语法是否正确
sudo redis-server /etc/redis/redis.conf --test-memory 10

# 重启服务以生效
sudo systemctl restart redis-server

第三步:启用开机自启

使用 systemd 管理可以使它随系统启动。

sudo systemctl enable redis-server

第四步:测试验证

测试连接

redis-cli

验证是否已生效:进入后测试连接性。

127.0.0.1:6379> auth 你的强密码
OK
127.0.0.1:6379> ping
PONG

看到 PONG 就代表 Redis 完全准备好了。