-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.php
71 lines (61 loc) · 2.48 KB
/
server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
use OpsWay\Doctrine\DBAL\Swoole\PgSQL\Scaler;
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
require_once 'vendor/autoload.php';
$connectionParams = [
// 'dbname' => 'postgres',
// 'user' => 'postgres',
// 'password' => 'postgres',
// 'host' => 'localhost',
'dbname' => 'mydb',
'user' => 'user',
'password' => 'secret',
'host' => 'dbhost',
'driverClass' => \OpsWay\Doctrine\DBAL\Swoole\PgSQL\Driver::class,
'poolSize' => 5, // MAX count connections in one pool
'tickFrequency' => 60000, // when need check possibilities downscale (close) opened connection to DB in pools
'connectionTtl' => 60, // when connection not used this time(seconds) - it will be close (free)
'usedTimes' => 100, // 1 connection (in pool) will be re-used maximum N queries
'connectionDelay' => 2, // time(seconds) for waiting response from pool
'useConnectionPool' => true, // if false, will create new connect instead of using pool
'retry' => [
'maxAttempts' => 2, // if connection in pool was timeout (before use) then try re-connect
'delay' => 1000, // delay to try fetch from pool again(milliseconds) if no connect available
]
];
$pool = (new \OpsWay\Doctrine\DBAL\Swoole\PgSQL\ConnectionPoolFactory())($connectionParams);
$configuration = new \Doctrine\DBAL\Configuration();
$configuration->setMiddlewares(
[new \OpsWay\Doctrine\DBAL\Swoole\PgSQL\DriverMiddleware($pool)]
);
$connFactory = static fn() => \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $configuration);
$scaler = new Scaler($pool, $connectionParams['tickFrequency']); // will try to free idle connect on connectionTtl overdue
$server = new Swoole\HTTP\Server("0.0.0.0", 9501);
$server->on("Start", function(Server $server)
{
echo "Swoole http server is started at http://0.0.0.0:9501\n";
});
$server->on("Request", function(Request $request, Response $response) use ($connFactory)
{
go(static function () use ($connFactory, $response) {
$conn = $connFactory();
$conn->fetchOne('SELECT version()');
$conn->fetchOne('SELECT pg_sleep(2)');
defer(static fn() => $conn->close());
$response->header("Content-Type", "text/plain");
$response->end('End');
});
});
$server->on('workerstart', function() use ($scaler)
{
$scaler->run();
});
$server->on('workerstop', function() use ($pool, $scaler)
{
$pool->close();
$scaler->close();
});
$server->start();