class SwooleServer
{
private $config = [
'Connections' => [
'min' => 5,
'max' => 10,
],
'Db' => [
'host' => '127.0.0.1',
'username' => 'test',
'password' => '123456',
'dbname' => 'test',
'charset' => 'utf8',
],
'Swoole' => [
'enable_static_handler' => true,
'document_root' => "/home/lixy/basic/web/",
'worker_num' => 5,
'task_worker_num' => 5,
'log_level' => 3,
],
'Channel' => [
'size' => 256 * 1024,
],
];
private $db_pool; // mysql链接内存队列
public function __construct()
{
$this->swoole = new \Swoole\Http\Server('0.0.0.0', 9502);
$this->swoole->set($this->config['Swoole']);
$this->swoole->on('task', [$this, 'task']);
$this->swoole->on('finish', [$this, 'finish']);
$this->swoole->on('request', [$this, 'request']);
$this->getDbPool();
}
public function getDbPool()
{
$connections = new MysqlConnections($this->config['Db']);
$quene = new Quene();
$this->db_pool = new DbPool($this->config['Connections']['max'], $this->config['Connections']['min']);
$this->db_pool->setConnection($connections);
$this->db_pool->setQuene($quene);
}
public function __call($name, $args)
{
return call_user_func_array([$this->swoole, $name], $args);
}
/**
* onrequest事件
* @param [type] $request 请求对象
* @param [type] $response 相应对象
* @return [type]
*/
public function request($request, $response)
{
$db = $this->db_pool->obtain();
echo 'get thread id : ' . $db->thread_id . PHP_EOL;
$sql = 'select * from test';
$result = $db->query($sql);
$this->db_pool->restitute($db);
$response->end('hello, response from swoole server');
}
public function task($serv, $task_id, $from_id, $data)
{
echo $task_id;
}
public function finish($serv, $task_id, $data)
{
echo $task_id;
}
}
$swoole_index = new SwooleServer();
$swoole_index->start();