插件窝 干货文章 如何在Linux中使用Redis缓存

如何在Linux中使用Redis缓存

Redis 缓存 user 设置 68    来源:    2025-04-18

在Linux中使用Redis缓存的完整指南

Redis是一个开源的高性能键值存储系统,常用于缓存、消息队列和数据库。以下是在Linux系统中使用Redis缓存的详细步骤:

1. 安装Redis

Ubuntu/Debian系统

sudo apt update
sudo apt install redis-server

CentOS/RHEL系统

sudo yum install epel-release
sudo yum install redis

从源代码编译安装

wget https://download.redis.io/releases/redis-6.2.6.tar.gz
tar xzf redis-6.2.6.tar.gz
cd redis-6.2.6
make
sudo make install

2. 启动Redis服务

# 启动Redis服务
sudo systemctl start redis

# 设置开机自启
sudo systemctl enable redis

# 检查服务状态
sudo systemctl status redis

3. 基本配置

编辑Redis配置文件(通常位于/etc/redis/redis.conf):

sudo nano /etc/redis/redis.conf

常用配置项: - bind 127.0.0.1 - 绑定IP地址 - port 6379 - 设置端口 - requirepass yourpassword - 设置密码 - maxmemory 256mb - 设置最大内存 - maxmemory-policy allkeys-lru - 内存满时的淘汰策略

修改后重启服务:

sudo systemctl restart redis

4. 使用Redis命令行工具

redis-cli

基本命令示例:

# 设置键值
SET mykey "Hello Redis"

# 获取值
GET mykey

# 设置带过期时间的键(10秒)
SETEX tempkey 10 "temporary value"

# 检查键是否存在
EXISTS mykey

# 删除键
DEL mykey

# 查看所有键
KEYS *

5. 在应用程序中使用Redis

Python示例 (使用redis-py)

import redis

# 连接Redis
r = redis.Redis(
    host='localhost',
    port=6379,
    password='yourpassword',
    decode_responses=True
)

# 设置值
r.set('foo', 'bar')

# 获取值
print(r.get('foo'))

# 设置带过期时间的键
r.setex('temp', 60, 'temporary value')

PHP示例 (使用Predis)

<?php
require 'predis/autoload.php';
Predis\Autoloader::register();

$redis = new Predis\Client([
    'scheme' => 'tcp',
    'host'   => '127.0.0.1',
    'port'   => 6379,
    'password' => 'yourpassword'
]);

$redis->set('foo', 'bar');
echo $redis->get('foo');
?>

6. 高级缓存策略

缓存雪崩防护

# 在配置文件中设置随机过期时间
maxmemory-policy volatile-ttl

缓存穿透防护

# Python示例 - 使用布隆过滤器或缓存空值
def get_user(user_id):
    # 先检查缓存
    user = r.get(f"user:{user_id}")
    if user is not None:
        return user if user != "NULL" else None

    # 数据库查询
    user = db.query_user(user_id)

    # 缓存结果,即使是空结果也缓存
    if user is None:
        r.setex(f"user:{user_id}", 300, "NULL")  # 缓存空值5分钟
    else:
        r.setex(f"user:{user_id}", 3600, user)  # 缓存正常值1小时

    return user

7. 监控与维护

# 查看Redis信息
redis-cli info

# 监控实时命令
redis-cli monitor

# 查看慢查询
redis-cli slowlog get

8. 安全建议

  1. 设置强密码
  2. 禁用危险命令: bash # 在redis.conf中添加: rename-command FLUSHDB "" rename-command FLUSHALL "" rename-command CONFIG ""
  3. 限制绑定IP
  4. 定期备份数据

通过以上步骤,您可以在Linux系统中有效地使用Redis作为缓存解决方案,提高应用程序性能。