Coroutine\Redis

推荐使用Swoole\Runtime::enableCoroutine + phpredis 或 predis 的 方式, 一键协程化原生PHP的redis客户端使用, 减小开发成本. 4.2.6版本及以后不再需要手动安装和启用async-redis, 而是swoole自带
  • 需要安装一个第三方的异步Redis库hiredis
  1. sudo make
  2. sudo make install
  3. sudo ldconfig
  • 需要在编译时增加—enable-async-redis来开启此功能
  • 请勿同时使用异步回调和协程Redis

使用示例


  1. $redis = new Swoole\Coroutine\Redis();
  2. $redis->connect('127.0.0.1', 6379);
  3. $val = $redis->get('key');

defer特性

  1. const REDIS_SERVER_HOST = '127.0.0.1';
  2. const REDIS_SERVER_PORT = 6379;
  3. go(function () {
  4. $redis = new Swoole\Coroutine\Redis();
  5. $redis->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT);
  6. $redis->setDefer();
  7. $redis->set('key1', 'value');
  8. $redis2 = new Swoole\Coroutine\Redis();
  9. $redis2->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT);
  10. $redis2->setDefer();
  11. $redis2->get('key1');
  12. $result1 = $redis->recv();
  13. $result2 = $redis2->recv();
  14. var_dump($result1, $result2);
  15. });

pipeline

Redis服务器支持多条指令并发执行。可使用defer特性启用pipeline

  1. const REDIS_SERVER_HOST = '127.0.0.1';
  2. const REDIS_SERVER_PORT = 6379;
  3. go(function () {
  4. $redis = new Swoole\Coroutine\Redis();
  5. $redis->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT);
  6. $redis->setDefer();
  7. $redis->set('key1', 'value');
  8. $redis->get('key1');
  9. $result1 = $redis->recv();
  10. $result2 = $redis->recv();
  11. var_dump($result1, $result2);
  12. });
subscribe pSubscribe无法用于defer(true)的情况。