温馨提示×

Centos Redis缓存如何配置

小樊
47
2026-07-20 03:14:02
栏目: 云计算

下面以 CentOS 7 / 8 为例,系统性地说明 Redis 缓存的配置方式,包括安装、基础配置、缓存优化、开机自启和常见使用方式。


一、Redis 安装(CentOS)

1️⃣ 安装方式一:yum(推荐)

# CentOS 7
yum install -y epel-release
yum install -y redis

# CentOS 8
dnf install -y redis

查看版本:

redis-server --version

2️⃣ 安装方式二:编译安装(可选)

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

二、Redis 基础配置(重点)

配置文件路径:

/etc/redis.conf        # yum 安装
/usr/local/redis/redis.conf  # 编译安装

1️⃣ 启动、停止、重启

systemctl start redis
systemctl enable redis
systemctl status redis

三、Redis 作为缓存的核心配置

编辑配置文件:

vim /etc/redis.conf

✅ 1. 监听地址(生产环境非常重要)

bind 0.0.0.0

或只允许本机:

bind 127.0.0.1

✅ 2. 设置密码(强烈推荐)

requirepass yourpassword

客户端连接:

redis-cli -a yourpassword

✅ 3. 配置最大内存(缓存核心)

maxmemory 512mb

策略(缓存必配):

maxmemory-policy allkeys-lru

常用策略说明:

策略 说明
noeviction 不淘汰,写满报错
allkeys-lru LRU 淘汰所有 key(最常用)
volatile-lru 只淘汰设置了过期时间的 key
allkeys-random 随机淘汰

缓存推荐:allkeys-lru


✅ 4. 设置后台运行

daemonize yes

✅ 5. 持久化配置(缓存一般不需要)

关闭持久化(纯缓存)

save ""
appendonly no

⚠️ 如果是为了高可用,可保留:

appendonly yes

四、Redis 作为本地缓存示例

1️⃣ 连接 Redis

redis-cli
127.0.0.1:6379> auth yourpassword
127.0.0.1:6379> set name redis
127.0.0.1:6379> get name

2️⃣ 设置缓存过期时间

SET key value EX 60   # 60秒过期

或:

EXPIRE key 60

五、应用程序中使用 Redis 缓存

Java(Spring Boot)

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);
}

PHP 示例

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('yourpassword');
$redis->set('name', 'redis', 60);

六、Redis 性能优化(缓存常用)

✅ 1. 关闭大页(Transparent Huge Pages)

echo never > /sys/kernel/mm/transparent_hugepage/enabled

写入开机启动:

vim /etc/rc.local

✅ 2. Linux 内核参数

vim /etc/sysctl.conf
vm.overcommit_memory = 1
net.core.somaxconn = 1024

生效:

sysctl -p

七、Redis 安全加固(生产必做)

✅ 设置密码
✅ 不要 bind 0.0.0.0 + 无密码
✅ 修改默认端口
✅ 使用防火墙限制访问

firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --reload

八、常见问题排查

Redis 启动失败

journalctl -u redis -xe

连接不上

  • 检查 bind
  • 检查 requirepass
  • 检查防火墙

九、总结(缓存最佳实践)

✅ 使用 allkeys-lru
✅ 限制 maxmemory
✅ 关闭持久化(纯缓存)
✅ 设置密码
✅ 应用层设置过期时间


如果你需要:

  • Redis 集群缓存
  • Redis + MySQL 缓存架构
  • CentOS 7/8 对比
  • Redis 缓存穿透 / 击穿 / 雪崩方案

可以直接告诉我你的使用场景(Web / 微服务 / 高并发)。

0