swoole 4.x 已弃用异步 redis,统一采用协程 redis 客户端(swoole\coroutine\redis),需在协程环境(如 go() 或 server 回调)中使用,依赖 swoole ≥ 4.4.0、php ≥ 7.2,无需 hiredis,支持连接复用与 pipeline 优化。

Swoole 4.x 版本已全面转向协程模型,不再提供独立的“异步 Redis”客户端(即旧版 --enable-async-redis 编译选项)。所谓“Swoole4 异步 Redis”,实际是指使用 Swoole\Coroutine\Redis 在协程内非阻塞地操作 Redis —— 这是当前高并发场景下的标准实践,性能更优、API 更简洁、无需 hiredis 编译依赖。
确认环境与基础依赖
确保以下条件满足,才能正常使用协程 Redis:
- PHP 版本 ≥ 7.2(推荐 8.0+),且已启用
sockets和pcntl扩展 - Swoole 扩展版本 ≥ 4.4.0(建议使用 4.8.x 或 5.x 稳定版),安装方式推荐 PECL:
pecl install swoole,然后在php.ini中添加extension=swoole.so - Redis 服务已独立部署并可访问(如本地
127.0.0.1:6379),无需额外装 hiredis 或重编译 Swoole - 运行时需在协程上下文中调用(如
go()、Swoole\Coroutine\run()或 Swoole HTTP/Server 回调中)
连接与基本操作示例
协程 Redis 客户端使用简单,自动复用连接、无回调嵌套:
use Swoole\Coroutine\Redis;
go(function () {
$redis = new Redis();
// 超时设为 2 秒,失败立即抛异常
$redis->setDefer(); // 可选:开启 defer 提升批量操作性能
if (!$redis->connect('127.0.0.1', 6379)) {
throw new RuntimeException("Redis connect failed");
}
$redis->set('user:1001', 'xiaoming');
$name = $redis->get('user:1001');
echo "Got: {$name}\n"; // 输出:Got: xiaoming
});
注意:不要在非协程环境(如普通 CLI 脚本或 Web SAPI)中直接 new Swoole\Coroutine\Redis,会报错 “cannot use coroutine class outside coroutine”。
Redis 缓存和数据结构管理技能。通过自然语言操作 Redis,支持 String、Hash、List、Set、ZSet、Stream 等数据结构操作。当用户提到 Redis、缓存、消息队列、会话存储时使用此技能。
高并发场景关键实践
单个协程 Redis 实例不跨协程共享,但可通过连接池或复用策略提升吞吐:
-
连接复用:每个协程内创建一次
new Redis()即可,Swoole 底层自动管理底层 socket 复用,无需手动池化 -
批量操作优化:用
setDefer()+commit()合并多个命令为 pipeline,减少网络往返
例如:$redis->setDefer(); $redis->hSet('hash', 'a', 1); $redis->hSet('hash', 'b', 2); $redis->commit(); -
错误处理必须显式:所有方法失败返回
false,需主动判断或配合try/catch(部分版本支持异常模式,可通过$redis->set(['serialize' => true])配合) -
避免阻塞调用混用:切勿在协程中穿插
sleep()、file_get_contents()、同步 cURL 等,改用co::sleep()和Swoole\Coroutine\Http\Client
验证是否就绪
执行以下命令检查核心组件状态:
php --ri swoole | grep -E "(Version|coroutine|redis)"
输出中应包含:
– Version => 4.8.13(或类似)
– support coroutines => enabled
– support redis client => enabled(该字段在 4.5+ 中默认存在,无需额外编译开关)
若缺失 redis client 支持,说明 Swoole 版本过低或安装不完整,建议升级至 4.8+ 并重新安装扩展。










