php mysql连接池测试,PHP实现基于Swoole的MySQL连接池

该博客展示了如何利用Swoole库创建一个高性能的HTTP服务器,配置包括连接池、数据库设置和任务处理。在request事件中,从连接池获取数据库连接执行SQL查询,并在完成后归还连接。Swoole Server监听9502端口,开启静态文件处理及工作进程和任务进程。
摘要由CSDN通过智能技术生成

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值