官方文檔中給出的示例是在onWorkerStart 中創(chuàng)建http_client并完成異步http請求,我的問題是如何實現(xiàn)在onWorkerStart創(chuàng)建,但是不調(diào)用,把調(diào)用放到onMessage中呢?
如果把創(chuàng)建對象及調(diào)用http請求都放在onMessage,應(yīng)該是可以實現(xiàn),但會創(chuàng)建很對對象出來,浪費資源,請問有什么好方法,解決這個問題?
$worker->onWorkerStart = function (){
global http_client;
$http_client = ...
};
$worker->onMessage = function($con, $message){
global http_client;
$http_client->xxxx...
};
高級點的用類包裝下。
class myClient
{
public $instance;
public function instance() {
if (!$this->instance) {
$this->instance = ....
}
return $this->instance;
}
}
用的時候直接
myClient->instance()->xxxx...
<?php
require_once __DIR__.'/vendor/autoload.php';
use Workerman\Worker;
$tcp_worker = new Worker('tcp://127.0.0.1:1234');
$tcp_worker->count = 1;
$tcp_worker->onWorkerStart = function (){
//方法一:全局變量+參照官方文檔創(chuàng)建一次對象
global $http_client;
$http_client = new Workerman\Http\Client();
//方法二:全局變量+用類包裝一下
global $client;
$client = new myClient();
};
$tcp_worker->onMessage = function ($connection,$data){
//方法一:獲取全局變量
global $http_client;
//方法一:調(diào)用全局變量
$http_client->get('http://www.example.com/',
function($response){
var_dump($response->getStatusCode());
echo $response->getBody();
},
function($exception){
echo $exception;
});
//方法二:獲取全局變量(類封裝)
global $client;
//方法二:調(diào)用全局變量
$client->instance()->get('http://www.example.com',
function ($response){
var_dump($response->getStatusCode());
echo $response->getBody();
},
function ($exception){
echo $exception;
});
//方法三:單例用法:
Singleton::getInstance()->get('http://www.example.com',
function ($response){
var_dump($response->getStatusCode());
echo $response->getBody();
},
function ($exception){
echo $exception;
});
};
Worker::runAll();
//類封裝
class myClient{
public $instance;
public function instance(){
if (!$this->instance){
$this->instance = new Workerman\Http\Client();
}
return $this->instance;
}
}
//單例
class Singleton{
//創(chuàng)建靜態(tài)私有的變量保存該類的對象
static private $instance;
//防止使用new直接創(chuàng)建對象
private function __construct(){}
//防止使用clone克隆對象
private function __clone(){}
static public function getInstance(){
//判斷$instance是否是http_client的對象,不是則創(chuàng)建
if (!self::$instance instanceof Workerman\Http\Client ){
self::$instance = new Workerman\Http\Client();
}
return self::$instance;
}
}
```貼上代碼,供新手學習,高手指點。