# 使用協程的優勢
Swoole是高性能異步框架,正因為異步所以高性能,但是異步也有異步的不好,寫邏輯代碼有時候就非常的不方便,需要多層嵌套回調,弄得代碼的可讀性很差維護起來非常的不方便,那么如何解決這個弊端呢?那就是使用協程。
SwooleDistributed框架提供了一套基于yield關鍵字的協程寫法。
#回調風格和協程風格的區別
舉例說明:
回調風格:
```php
/**
* mysql 測試
* @throws \Server\CoreBase\SwooleException
*/
public function mysql_test()
{
$this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('sex', 1);
$this->mysql_pool->query(function ($result) {
print_r($result);
$this->destroy();
});
}
```
協程風格:
```php
/**
* mysql 測試
* @throws \Server\CoreBase\SwooleException
*/
public function mysql_test()
{
$mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('sex', 1)->coroutineSend();
$result = yield $mySqlCoroutine;
print_r($result);
$this->destroy();
}
```
上述代碼還只是基礎,想想看多次請求并且依賴的情況
回調風格:
```php
public function test($callback)
{
$this->redis_pool->get('test',function ($uid)use($callback){
$this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', $uid);
$this->mysql_pool->query(function ($result)use($callback) {
call_user_func($callback,$result);
});
});
}
```
協程風格:
```php
public function test()
{
$redisCoroutine = $this->redis_pool->getCoroutine()->get('test');
$uid = yield $redisCoroutine;
$mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', $uid)->coroutineSend();
$result = yield $mySqlCoroutine;
return $result;
}
```
上面的代碼是在一個model中,按照以往的回調風格,controller調用這個model還需要傳進去一個回調函數才能獲取到值(我覺得這么做的人一定會瘋),而協程風格你只需要按部就班的return結果就行了。和同步的代碼唯一的區別就是多了一個yield關鍵字。
好了我們再看調用這個model的controller怎么寫。
回調風格:
```php
/**
* 非協程測試
*/
public function http_testNOCoroutine()
{
$this->testModel = $this->loader->model('TestModel', $this);
$this->testModel->test(function($result){
$this->http_output->end($result);
});
}
```
協程風格:
```php
/**
* 協程測試
*/
public function http_testCoroutine()
{
$this->testModel = $this->loader->model('TestModel', $this);
$result = yield $this->testModel->test();
$this->http_output->end($result);
}
```
同樣只是要多加一個yield關鍵字。是不是很方便~,注意只有這個model的方法內使用了yield,控制器調用的時候才需要加yield關鍵字。普通的方法是不需要的,當然你加了也不會報錯。
# 協程中的異常?
swooleDistributed框架已經將協程的使用變得很方便了,至于異常和平常的寫法一毛一樣。
```php
public function test_exceptionII()
{
$mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', 10303)->coroutineSend();
$result = yield $mySqlCoroutine;
throw new \Exception('test');
}
```
無論你是在model中還是在controller中,還是在model的model中。。。。
總之throw出來就行,上一層使用try可以捕獲到錯誤。
這里還有個小小的體驗優化,當報錯一直到controller層的時候,會被controller的onExceptionHandle捕獲到,你可以重寫這個函數實現異常情況下的客戶端回復。
# 協程的嵌套
支持無限級的嵌套。
# 協程的調度順序
調節yield的位置即可調節接收的順序。
```php
$redisCoroutine = $this->redis_pool->getCoroutine()->get('test');
$uid = yield $redisCoroutine;
$mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', $uid)->coroutineSend();
$result = yield $mySqlCoroutine;
```
上面的代碼調度順序是redis_send->redis_rev->mysql_send->mysql_rev。
```php
$redisCoroutine = $this->redis_pool->getCoroutine()->get('test');
$mySqlCoroutine = $this->mysql_pool->dbQueryBuilder->select('*')->from('account')->where('uid', 123)->coroutineSend();
$uid = yield $redisCoroutine;
$result = yield $mySqlCoroutine;
```
上面的代碼調度順序是redis_send->mysql_send->redis_rev->mysql_rev。
- Introduction
- SD 3.X文檔連接
- 導言
- 用戶案例
- 基于Swoole擴展分布式全棧開發框架
- 選擇SD框架助力企業開發
- 捐贈SwooleDistributed項目
- 框架性能報告
- 更新日志
- VIP服務福利
- 安裝與配置
- 【推薦】全自動安裝部署
- 環境要求
- 使用Composer安裝/更新SD框架
- 通過Docker安裝
- 代碼結構
- 啟動命令
- 服務器配置
- 服務器基礎配置server.php
- 客戶端協議配置client.php
- business.php
- log.php
- 微服務及集群配置consul.php
- fileHeader.php
- mysql.php
- redis.php
- 定時任務配置timerTask.php
- 服務器端口配置ports.php
- catCache.php
- 驗證服務啟動成功
- 微服務-Consul
- 日志工具-GrayLog
- 集群-Cluster
- 內核優化
- 入門教學
- 開發流程
- 開發前必讀
- 開發規范
- 基本流程
- 框架入口
- Model數據模型
- Controller控制器
- 協程
- 協程基礎
- 迭代器
- 調度器
- 使用協程的優勢
- 通過協程的方法屏蔽異步同步的區別
- Select多路選擇器
- 協程Sleep
- 通用協程方法
- 設置超時
- 設置無異常
- 設置降級函數
- initAsynPools
- dump
- 封裝器與路由器
- 封裝器
- sendToUid
- 路由器
- sendToUids
- 對象池
- 擴展組件
- 中間件
- Redis使用介紹
- RedisAsynPool
- Redis具體使用
- sendToAll
- RedisRoute
- Redis+Lua
- Mysql使用介紹
- MysqlAsynPool
- Mysql返回值
- 如何獲取構建的mysql語句
- 如何執行一個SQL
- 如何執行事務
- stopTask
- Mysql具體使用
- 異步客戶端
- Loader
- MqttClient
- model
- SdTcpRpcPool
- task
- HttpClientPool
- view
- TcpClientPool
- AMQP
- initialization
- Memory
- destory
- Cache
- Lock
- Pool
- EventDispatcher
- Process
- Cluster
- TimerTask
- Reload
- Consul
- Context
- 自定義進程
- 進程間RPC
- $http_input
- CatCache
- $http_output
- TimerCallBack
- 專題
- HTTP專欄
- TCP專欄
- 基礎知識
- WebSocket專欄
- 微服務
- Consul配置
- RPC
- REST
- AMQP異步任務系統
- MQTT簡易服務器
- Docker化以及資源編排
- 快速搭建公司內部統一的開發環境
- 使用HTTPS/WSS
- 訂閱/發布
- 游戲專題
- 類介紹
- AppServer
- clearState
- onOpenServiceInitialization
- SwooleDistributedServer
- get_instance
- kickUid
- bindUid
- unBindUid
- coroutineUidIsOnline
- coroutineCountOnline
- setTemplateEngine
- isWebSocket
- isTaskWorker
- getSocketName
- initAsynPools
- addAsynPool
- getAsynPool
- getServerAllTaskMessage
- Controller
- onExceptionHandle
- send
- sendToUid
- sendToUids
- sendToAll
- sendToGroup
- close
- getContext
- defaultMethod
- $redis_pool
- $mysql_pool
- $request_type
- $fd
- $uid
- $client_data
- $request
- $response
- $loader
- $logger
- $server
- $config
- Model
- initialization
- destory
- View
- Task
- stopTask
- HttpInput
- postGet
- post
- get
- getPost
- getAllPostGet
- getAllHeader
- getRawContent
- cookie
- getRequestHeader
- server信息
- getRequestMethod
- getRequestUri
- getPathInfo
- HttpOutput
- setStatusHeader
- setContentType
- setHeader
- end
- setCookie
- endFile
- 單元測試