助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
# Coroutine\\Redis [TOC] > 推荐使用`Swoole\Runtime::enableCoroutine`\+ phpredis 或 predis 的 方式, 一键协程化原生PHP的redis客户端使用, 减小开发成本. > > 4.2.6版本及以后不再需要手动安装和启用async-redis, 而是swoole自带 * 需要安装一个第三方的异步Redis库[hiredis](https://github.com/redis/hiredis) ~~~ sudo make sudo make install sudo ldconfig ~~~ * 需要在编译时增加`--enable-async-redis`来开启此功能 * **请勿同时使用异步回调和协程`Redis`** ## 使用示例 * * * ~~~ $redis = new Swoole\Coroutine\Redis(); $redis->connect('127.0.0.1', 6379); $val = $redis->get('key'); ~~~ ## defer特性 ~~~ const REDIS_SERVER_HOST = '127.0.0.1'; const REDIS_SERVER_PORT = 6379; go(function () { $redis = new Swoole\Coroutine\Redis(); $redis->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT); $redis->setDefer(); $redis->set('key1', 'value'); $redis2 = new Swoole\Coroutine\Redis(); $redis2->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT); $redis2->setDefer(); $redis2->get('key1'); $result1 = $redis->recv(); $result2 = $redis2->recv(); var_dump($result1, $result2); }); ~~~ ## pipeline `Redis`服务器支持多条指令并发执行。可使用`defer`特性启用`pipeline` ~~~ const REDIS_SERVER_HOST = '127.0.0.1'; const REDIS_SERVER_PORT = 6379; go(function () { $redis = new Swoole\Coroutine\Redis(); $redis->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT); $redis->setDefer(); $redis->set('key1', 'value'); $redis->get('key1'); $result1 = $redis->recv(); $result2 = $redis->recv(); var_dump($result1, $result2); }); ~~~ > `subscribe pSubscribe`无法用于defer(true)的情况。