使用 php 中的 redis 扩展可轻松操作 redis 数据库,包括连接、设置/获取键值对、删除键、检查键是否存在、设置过期时间、增量值、执行事务、操作队列以及进行发布/订阅。
使用 PHP 连接和操作 Redis
PHP 中可以使用 redis 扩展来连接和操作 Redis 数据库。
安装
使用 Composer 安装 redis 扩展:
<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15906.html" target="_blank">composer</a> require predis/predis
连接 Redis 数据库
// 连接到 localhost:6379 的 Redis 数据库
$redis = new PredisClient();
// 连接到使用密码保护的 Redis 数据库,port 默认是 6379
// $redis = new PredisClient([
// 'host' => 'localhost',
// 'password' => 'my-password'
// ]);
设置键值对
// 设置键值对
$redis->set('name', 'John Doe');
获取键值
// 获取键值
$name = $redis->get('name');
其他操作
// 删除键值
$redis->del('name');
// 检查键是否存在
$exists = $redis->exists('name');
// 为键值设置过期时间
$redis->expire('name', 300); // 5 分钟
// 原子性地增量值
$redis->incrby('counter', 1);
事务
// 开始事务
$redis->multi();
// 执行多个操作
$redis->set('key1', 'value1');
$redis->del('key2');
// 提交事务
$redis->exec();
队列
// 将消息添加到队列
$redis->lpush('queue', 'message');
// 从队列中取出消息
$message = $redis->rpop('queue');
发布/订阅
// 订阅频道
$redis->subscribe('channel1', 'channel2');
// 处理收到的消息
$redis->on('message', function($channel, $message) {
// ...
});