Redis - Php
Redis 与现代 PHP
Section titled “Redis 与现代 PHP”使用 Composer 进行依赖管理,将 Redis 集成到现代 PHP 应用程序中非常简单。Redis 客户端主要有两个选择:
- PhpRedis: 一个用 C 语言编写的 PHP 扩展。它速度极快,但需要在服务器上安装(例如,通过 PECL)。
- Predis: 一个纯 PHP 客户端库。它速度略慢,但无需特殊扩展,只需
composer require。
对于新项目,Predis 通常是最容易上手的。这些示例我们将使用 Predis。
1. 项目设置(Composer)
Section titled “1. 项目设置(Composer)”在你的项目目录中,运行以下命令将 Predis 添加到你的项目中:
composer require predis/predis然后,在你的 PHP 脚本中引入 Composer 的自动加载器(autoloader)。
<?php
require 'vendor/autoload.php';2. 连接到 Redis
Section titled “2. 连接到 Redis”实例化 Predis 客户端。将你的 Redis 逻辑封装在 try...catch 块中以处理潜在的连接错误是一个好习惯。
<?php
require 'vendor/autoload.php';
try { $redis = new Predis\Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]);
echo "Connection to server successfully" . PHP_EOL; // 检查连接 $ping = $redis->ping(); echo "Server is running: " . $ping . PHP_EOL;
} catch (Exception $e) { die("Could not connect to Redis: " . $e->getMessage());}程序执行后,将产生以下结果:
Connection to server successfullyServer is running: PONG3. 代码示例
Section titled “3. 代码示例”以下示例假定你已拥有如上所示的 $redis 客户端对象。
<?php// ... (自动加载器和连接)
$key = 'tutorial-name';$value = 'Modern Redis with PHP';
$redis->set($key, $value);$retrievedValue = $redis->get($key);
echo "Stored string in redis: " . $retrievedValue . PHP_EOL;<?php// ... (自动加载器和连接)
$listKey = 'frameworks';
// 在运行示例前清除旧的列表项$redis->del($listKey);
$redis->lpush($listKey, ['Laravel', 'Symfony', 'Yii']);
$frameworks = $redis->lrange($listKey, 0, -1);
echo "PHP Frameworks: " . PHP_EOL;print_r($frameworks);键示例(使用 SCAN)
Section titled “键示例(使用 SCAN)”警告: 切勿在生产环境中使用 KEYS *,因为它会阻塞你的服务器。安全、现代的替代方案是使用利用 SCAN 命令的迭代器。
<?php// ... (自动加载器和连接)
use Predis\Collection\Iterator\Keyspace;
// 添加一些示例键用于演示$redis->set('user:1', 'Alice');$redis->set('user:2', 'Bob');$redis->set('config:theme', 'dark');
echo "\nScanning for keys with pattern 'user:*':" . PHP_EOL;
$matchingKeys = [];// Predis 提供了一个方便的迭代器,它在内部处理 SCAN 逻辑foreach (new Keyspace($redis, 'user:*') as $key) { $matchingKeys[] = $key;}
print_r($matchingKeys);最佳实践与框架
Section titled “最佳实践与框架”在大型应用程序中,你通常会通过 Laravel 或 Symfony 等框架提供的抽象层与 Redis 交互。它们处理配置、连接池,并为使用 Redis 进行缓存、会话管理和队列提供清晰流畅的 API。