引言:
PHP 调用 Redis 数据库主要通过 PhpRedis 扩展或 Predis 客户端实现。本文系统介绍 Redis 服务安装、PhpRedis 与 Predis 的连接配置、字符串/哈希/列表/集合等数据结构操作,以及缓存、会话存储、限流计数器等典型应用场景,帮助 PHP 开发者快速集成 Redis 高性能内存数据库。

PHP 与 Redis 数据库调用完全指南

Redis 是一个高性能的内存数据库,常用于缓存、会话管理和实时分析场景。在 PHP 中调用 Redis,主要通过两种官方推荐的客户端实现:PhpRedis(C 扩展)和 Predis(纯 PHP 库)。本文将系统讲解安装配置、连接操作、数据读写及典型应用场景。

一、环境准备:安装 Redis 服务

在开始 PHP 调用之前,需要确保 Redis 服务已经安装并运行。

Ubuntu/Debian 系统

1
2
3
4
sudo apt-get update
sudo apt-get install redis-server
sudo systemctl start redis-server
sudo systemctl status redis-server # 检查运行状态

CentOS/RedHat 系统

1
2
sudo yum install redis
sudo systemctl start redis

验证 Redis 正常运行:

1
2
redis-cli ping
# 应返回 PONG

二、PHP Redis 客户端的选择与安装

PHP 连接 Redis 主要有两种方式,选择取决于你的环境需求。

方案一:PhpRedis(推荐,性能更优)

PhpRedis 是用 C 语言编写的 PHP 扩展,性能更高,是生产环境的首选方案。它通过 PECL 安装:

1
2
# 安装 PhpRedis 扩展
pecl install redis

安装完成后,在 php.ini 中添加以下配置启用扩展:

1
extension=redis.so

然后重启 Web 服务器或 PHP-FPM 使配置生效。你可以通过 php -m | grep redisphpinfo() 确认扩展已成功加载。

各系统快捷安装方式

系统 命令
Ubuntu/Debian sudo apt-get install php-redis
CentOS/RedHat yum install php-devel php-common php-cli(然后通过 PECL 安装)

方案二:Predis(纯 PHP 实现)

Predis 是一个纯 PHP 编写的 Redis 客户端,无需编译扩展,适合无法安装 C 扩展的环境。通过 Composer 安装:

1
composer require predis/predis

在代码中通过 Composer 自动加载即可使用。

三、建立与 Redis 的连接

使用 PhpRedis 连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$redis = new Redis();

// 基本连接(主机,端口,超时时间)
$redis->connect('127.0.0.1', 6379, 2.5);

// 如果设置了密码,进行认证
$redis->auth('your_password');

// 选择数据库(默认 0)
$redis->select(0);

// 测试连接
echo $redis->ping(); // 输出 "PONG"
?>

连接参数说明:

  • host:Redis 服务器地址(IP 或域名)
  • port:端口号,默认 6379
  • timeout:连接超时时间(秒)
  • auth:认证密码(如已设置)

使用 Predis 连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
require 'vendor/autoload.php';

use Predis\Client as PredisClient;

$client = new PredisClient([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'your_password',
'database' => 0,
]);

// 测试连接
echo $client->ping(); // 输出 "PONG"
?>

四、数据读写操作(CRUD)

字符串操作

字符串是 Redis 最基础的数据类型,适合缓存简单的键值对数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 写入字符串
$redis->set('user:1:name', '张三');

// 读取字符串
$name = $redis->get('user:1:name');
echo $name; // "张三"

// 设置带过期时间的键(60秒后自动删除)
$redis->setex('session_token', 60, 'abc123');

// 删除键
$redis->del('user:1:name');

// 检查键是否存在
if ($redis->exists('user:1:name')) {
echo "键存在";
}

哈希表操作

哈希表适合存储对象或结构化数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 设置哈希表字段
$redis->hSet('user:100', 'name', '李四');
$redis->hSet('user:100', 'email', 'lisi@example.com');
$redis->hSet('user:100', 'age', 28);

// 读取单个字段
$name = $redis->hGet('user:100', 'name');

// 读取全部字段
$user = $redis->hGetAll('user:100');
print_r($user);
// Array ( [name] => 李四 [email] => lisi@example.com [age] => 28 )

// 删除字段
$redis->hDel('user:100', 'age');

列表操作

列表适合实现消息队列、历史记录等场景。

1
2
3
4
5
6
7
8
9
10
11
12
13
// 从列表左侧推入(先进后出)
$redis->lPush('task_queue', 'task1');
$redis->lPush('task_queue', 'task2');

// 从列表右侧推入(先进先出)
$redis->rPush('task_queue', 'task3');

// 获取列表范围内元素(索引 0 到 -1 表示全部)
$tasks = $redis->lRange('task_queue', 0, -1);
print_r($tasks); // Array ( [0] => task2 [1] => task1 [2] => task3 )

// 从右侧弹出(FIFO 队列)
$task = $redis->rPop('task_queue'); // "task1"

集合操作

集合适合存储不重复的元素,支持交集、并集等操作。

1
2
3
4
5
6
7
8
9
10
11
// 向集合添加成员
$redis->sAdd('tags:php', 'web', 'backend', 'laravel');
$redis->sAdd('tags:javascript', 'web', 'frontend', 'react');

// 获取集合所有成员
$phpTags = $redis->sMembers('tags:php');
// Array ( [0] => web [1] => backend [2] => laravel )

// 取交集(同时属于两个集合的元素)
$common = $redis->sInter('tags:php', 'tags:javascript');
// Array ( [0] => web )

五、典型应用场景

场景一:数据缓存(减轻数据库压力)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$cacheKey = 'products:featured';

// 先尝试从缓存读取
$cached = $redis->get($cacheKey);

if ($cached !== false) {
// 缓存命中,直接返回
$products = json_decode($cached, true);
} else {
// 缓存未命中,从数据库查询
$products = fetchFeaturedProductsFromDb(); // 假设的数据库查询函数
// 写入缓存,有效期 5 分钟
$redis->setex($cacheKey, 300, json_encode($products));
}

// 使用 $products 数据
?>

场景二:PHP 会话存储

PhpRedis 支持将 PHP 会话直接存储在 Redis 中,适合多服务器分布式部署。在 php.ini 中配置:

1
2
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"

如果 Redis 有密码认证:

1
session.save_path = "tcp://127.0.0.1:6379?auth=your_password"

支持多服务器负载均衡:

1
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2"

场景三:计数器与限流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 文章阅读数累加
$redis->incr('article:123:views');

// 获取当前阅读数
$views = $redis->get('article:123:views');

// 滑动窗口限流(每分钟最多 10 次请求)
$key = 'rate_limit:' . $user_id;
$current = $redis->incr($key);
if ($current == 1) {
$redis->expire($key, 60); // 首次设置过期时间
}
if ($current > 10) {
die("请求过于频繁,请稍后再试");
}

六、错误处理与最佳实践

连接错误处理

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$redis = new Redis();
try {
if ($redis->connect('127.0.0.1', 6379) == false) {
die($redis->getLastError());
}
if ($redis->auth('password') == false) {
die($redis->getLastError());
}
} catch (RedisException $e) {
echo "Redis 连接失败:" . $e->getMessage();
}
?>

连接关闭

1
$redis->close(); // 关闭连接

最佳实践建议

建议 说明
设置合理的过期时间 避免内存无限增长,使用 setex()expire()
生产环境使用 PhpRedis 性能优于 Predis
避免大键(Big Keys) 单键数据过大可能导致性能问题
使用连接池或持久连接 减少频繁创建连接的开销
密码避免硬编码 使用环境变量存储 Redis 密码

总结

PHP 调用 Redis 的核心流程分为三步:

  1. 安装扩展:通过 PECL 安装 PhpRedis(或通过 Composer 安装 Predis)
  2. 建立连接:使用 new Redis()connect() 方法连接 Redis 服务
  3. 执行操作:使用 set()get()hSet() 等方法进行数据读写

掌握这些基础操作后,可以进一步探索 Redis 的更多高级特性,如发布订阅、流水线(Pipeline)、事务(Multi/Exec)以及集群连接等。