MongoDb

目前,MongoDB并没有提供协程版本的php客户端,只有同步阻塞版本。

::: tip 提示 EasySwoole 的协程版客户端已经在排期内。 :::

在实际生产中,直接 创建原生的mongoDB客户端来进行数据交互,也不是不可。

若希望将同步调用转为协程调用,可以用Easyswoole 提供的sync-invoker组件。

定义驱动

  1. namespace App\Mongodb;
  2. use EasySwoole\EasySwoole\Trigger;
  3. use EasySwoole\SyncInvoker\AbstractInvoker;
  4. use MongoDB\Client;
  5. class Driver extends AbstractInvoker
  6. {
  7. private $db;
  8. function getDb():Client
  9. {
  10. if($this->db == null){
  11. $mongoUrl = "mongodb://127.0.0.1:27017";
  12. $this->db = new Client($mongoUrl);
  13. }
  14. return $this->db;
  15. }
  16. protected function onException(\Throwable $throwable)
  17. {
  18. Trigger::getInstance()->throwable($throwable);
  19. return null;
  20. }
  21. }

客户端

  1. namespace App\Mongodb;
  2. use EasySwoole\Component\Singleton;
  3. use EasySwoole\SyncInvoker\SyncInvoker;
  4. class MongoClient extends SyncInvoker
  5. {
  6. use Singleton;
  7. }

服务注册

在Easyswoole全局事件mainServerCreate中进行服务注册

  1. MongoClient::getInstance(new Driver())->attachServer(ServerManager::getInstance()->getSwooleServer());

开始使用

  1. $ret = MongoClient::getInstance()->client()->callback(function (Driver $driver){
  2. $ret = $driver->getDb()->user->list->insertOne([
  3. 'name' =>Random::character(8),
  4. 'sex'=>'man',
  5. ]);
  6. if(!$ret){
  7. return false;
  8. }
  9. return $ret->getInsertedId();
  10. });
  11. $ret = MongoClient::getInstance()->client()->callback(function (Driver $driver){
  12. $ret = [];
  13. $collections = $driver->getDb()->user->listCollections();
  14. foreach ($collections as $collection) {
  15. $ret[] = (array)$collection;
  16. }
  17. return $ret;
  18. });