Skip to content

Commit

Permalink
redis,mysql协程连接池加入调用次数矫正,防止极端情况下的超调用
Browse files Browse the repository at this point in the history
  • Loading branch information
bingcool committed May 24, 2019
1 parent d2ce3dd commit 5e33d15
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion score/Core/ComponentTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ public function __get($name) {
if(in_array($name, $this->component_pools)) {
$poolHandler = \Swoolefy\Core\Coroutine\CoroutinePools::getInstance()->getPool($name);
if(is_object($poolHandler)) {
$this->container[$name] = $poolHandler->getObj();
$this->container[$name] = $poolHandler->fetchObj();
}
// 如果没有设置进程池处理实例,则降级到创建实例模式
if(isset($this->container[$name]) && is_object($this->container[$name])) {
Expand Down
3 changes: 3 additions & 0 deletions score/Core/Coroutine/CoroutinePools.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ public function addPool(string $pool_name, $handler) {
* @return mixed
*/
public function getPool(string $pool_name) {
if(!$pool_name) {
return null;
}
$pool_name = trim($pool_name);
if(isset($this->pools[$pool_name])) {
return $this->pools[$pool_name];
Expand Down
20 changes: 19 additions & 1 deletion score/Core/Coroutine/PoolsHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ abstract class PoolsHandler {

protected $popTimeout = 1;

protected $callCount = 0;

public function setMaxPoolsNum(int $maxPoolsNum = 50) {
$this->maxPoolsNum = $maxPoolsNum;
}
Expand Down Expand Up @@ -88,11 +90,27 @@ public function registerPools(string $pool_name = null) {
public function pushObj($obj) {
if(is_object($obj)) {
go(function() use($obj) {
$this->channel->push($obj, $this->pushTimeout);
$result = $this->channel->push($obj, $this->pushTimeout);
$length = $this->channel->length();
// 矫正
if(($this->maxPoolsNum - $length) == $this->callCount - 1) {
$this->callCount--;
}else {
$this->callCount = $this->maxPoolsNum - $length;
}
});
}
}

public function fetchObj() {
try {
$this->callCount++;
return $this->getObj();
}catch(\Exception $e) {
throw new \Exception($e->getMessage());
}
}

/**
* getObj 开发者自行实现
* @return
Expand Down

0 comments on commit 5e33d15

Please sign in to comment.