下面以 CentOS 7 / 8 为例,系统性地说明 Redis 缓存的配置方式,包括安装、基础配置、缓存优化、开机自启和常见使用方式。
# CentOS 7
yum install -y epel-release
yum install -y redis
# CentOS 8
dnf install -y redis
查看版本:
redis-server --version
yum install -y gcc make
cd /usr/local/src
wget https://download.redis.io/releases/redis-7.2.6.tar.gz
tar -zxvf redis-7.2.6.tar.gz
cd redis-7.2.6
make
make install
配置文件路径:
/etc/redis.conf # yum 安装
/usr/local/redis/redis.conf # 编译安装
systemctl start redis
systemctl enable redis
systemctl status redis
编辑配置文件:
vim /etc/redis.conf
bind 0.0.0.0
或只允许本机:
bind 127.0.0.1
requirepass yourpassword
客户端连接:
redis-cli -a yourpassword
maxmemory 512mb
策略(缓存必配):
maxmemory-policy allkeys-lru
常用策略说明:
| 策略 | 说明 |
|---|---|
noeviction |
不淘汰,写满报错 |
allkeys-lru |
LRU 淘汰所有 key(最常用) |
volatile-lru |
只淘汰设置了过期时间的 key |
allkeys-random |
随机淘汰 |
✅ 缓存推荐:allkeys-lru
daemonize yes
关闭持久化(纯缓存)
save ""
appendonly no
⚠️ 如果是为了高可用,可保留:
appendonly yes
redis-cli
127.0.0.1:6379> auth yourpassword
127.0.0.1:6379> set name redis
127.0.0.1:6379> get name
SET key value EX 60 # 60秒过期
或:
EXPIRE key 60
spring:
redis:
host: 127.0.0.1
port: 6379
password: yourpassword
timeout: 2000
注解缓存:
@Cacheable(value = "user", key = "#id")
public User getUserById(Long id) {
return userMapper.selectById(id);
}
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('yourpassword');
$redis->set('name', 'redis', 60);
echo never > /sys/kernel/mm/transparent_hugepage/enabled
写入开机启动:
vim /etc/rc.local
vim /etc/sysctl.conf
vm.overcommit_memory = 1
net.core.somaxconn = 1024
生效:
sysctl -p
✅ 设置密码
✅ 不要 bind 0.0.0.0 + 无密码
✅ 修改默认端口
✅ 使用防火墙限制访问
firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --reload
journalctl -u redis -xe
bindrequirepass✅ 使用 allkeys-lru
✅ 限制 maxmemory
✅ 关闭持久化(纯缓存)
✅ 设置密码
✅ 应用层设置过期时间
如果你需要:
可以直接告诉我你的使用场景(Web / 微服务 / 高并发)。