Ver código fonte

Optimize test script (#3841)

* Strong type and PSR code style.

* Reuse prepared statement.

* Fix type.
twosee 7 anos atrás
pai
commit
f7c13c34e1
1 arquivos alterados com 86 adições e 74 exclusões
  1. 86 74
      frameworks/PHP/swoole/swoole-server.php

+ 86 - 74
frameworks/PHP/swoole/swoole-server.php

@@ -1,8 +1,12 @@
 <?php
 <?php
+
+use Swoole\Http\Request;
+use Swoole\Http\Response;
+
 $server = new swoole_http_server('0.0.0.0', 8080, SWOOLE_BASE);
 $server = new swoole_http_server('0.0.0.0', 8080, SWOOLE_BASE);
-$server->set(array(
+$server->set([
     'worker_num' => NUMCORES
     'worker_num' => NUMCORES
-));
+]);
 
 
 $pool = new DatabasePool();
 $pool = new DatabasePool();
 
 
@@ -10,37 +14,38 @@ $pool = new DatabasePool();
  * The DB test
  * The DB test
  *
  *
  * @param string $database_type
  * @param string $database_type
- * @param int    $queries
+ * @param int $queries
  *
  *
  * @return string
  * @return string
  */
  */
-$db = function ($database_type, $queries = 0) use ($pool) {
+$db = function (string $database_type, int $queries = 0) use ($pool): string {
     $db = $pool->get($database_type);
     $db = $pool->get($database_type);
 
 
     // Read number of queries to run from URL parameter
     // Read number of queries to run from URL parameter
     $query_count = 1;
     $query_count = 1;
-    if ($queries > 0)
+    if ($queries > 0) {
         $query_count = $queries > 500 ? 500 : $queries;
         $query_count = $queries > 500 ? 500 : $queries;
+    }
 
 
     // Create an array with the response string.
     // Create an array with the response string.
-    $arr = array();
+    $arr = [];
     // Define query
     // Define query
-    $stmt = $db->prepare('SELECT randomNumber FROM World WHERE id = ?');
+    $db->db_test = $db->db_test ?? $db->prepare('SELECT randomNumber FROM World WHERE id = ?');
 
 
     // For each query, store the result set values in the response array
     // For each query, store the result set values in the response array
-    while (0 < $query_count--)
-    {
+    while (0 < $query_count--) {
         $id = mt_rand(1, 10000);
         $id = mt_rand(1, 10000);
-        $ret = $stmt->execute(array($id));
+        $ret = $db->db_test->execute([$id]);
 
 
         // Store result in array.
         // Store result in array.
-        $arr[] = array('id' => $id, 'randomNumber' => $ret[0]['randomNumber']);
+        $arr[] = ['id' => $id, 'randomNumber' => $ret[0]['randomNumber']];
     }
     }
 
 
     // Use the PHP standard JSON encoder.
     // Use the PHP standard JSON encoder.
     // http://www.php.net/manual/en/function.json-encode.php
     // http://www.php.net/manual/en/function.json-encode.php
-    if ($queries == -1)
+    if ($queries === -1) {
         $arr = $arr[0];
         $arr = $arr[0];
+    }
 
 
     $pool->put($db);
     $pool->put($db);
 
 
@@ -54,22 +59,25 @@ $db = function ($database_type, $queries = 0) use ($pool) {
  *
  *
  * @return string
  * @return string
  */
  */
-$fortunes = function ($database_type) use ($pool) {
+$fortunes = function (string $database_type) use ($pool): string {
     $db = $pool->get($database_type);
     $db = $pool->get($database_type);
 
 
     $fortune = [];
     $fortune = [];
-    // Define query
-    $arr = $db->query('SELECT id, message FROM Fortune');
-    foreach ($arr as $row)
+    $db->fortune_test = $db->fortune_test ?? $db->prepare('SELECT id, message FROM Fortune');
+    $arr = $db->fortune_test->execute([]);
+    foreach ($arr as $row) {
         $fortune[$row['id']] = $row['message'];
         $fortune[$row['id']] = $row['message'];
+    }
     $fortune[0] = 'Additional fortune added at request time.';
     $fortune[0] = 'Additional fortune added at request time.';
     asort($fortune);
     asort($fortune);
 
 
-    $html = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
-    foreach ($fortune as $id => $message)
-        $html .= "<tr><td>" . $id . "</td><td>" . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . "</td></tr>";
+    $html = '<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>';
+    foreach ($fortune as $id => $message) {
+        $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
+        $html .= "<tr><td>{$id}</td><td>{$message}</td></tr>";
+    }
 
 
-    $html .= "</table></body></html>";
+    $html .= '</table></body></html>';
 
 
     $pool->put($db);
     $pool->put($db);
 
 
@@ -80,31 +88,31 @@ $fortunes = function ($database_type) use ($pool) {
  * The Updates test
  * The Updates test
  *
  *
  * @param string $database_type
  * @param string $database_type
- * @param int    $queries
+ * @param int $queries
  *
  *
  * @return string
  * @return string
  */
  */
-$updates = function ($database_type, $queries = 0) use ($pool) {
+$updates = function (string $database_type, int $queries = 0) use ($pool): string {
     $db = $pool->get($database_type);
     $db = $pool->get($database_type);
 
 
     $query_count = 1;
     $query_count = 1;
-    if ($queries > 0)
+    if ($queries > 0) {
         $query_count = $queries > 500 ? 500 : $queries;
         $query_count = $queries > 500 ? 500 : $queries;
+    }
 
 
-    $arr = array();
-    $statement = $db->prepare('SELECT randomNumber FROM World WHERE id = ?');
-    $updateStatement = $db->prepare('UPDATE World SET randomNumber = ? WHERE id = ?');
+    $arr = [];
+    $db->updates_test_select = $db->updates_test_select ?? $db->prepare('SELECT randomNumber FROM World WHERE id = ?');
+    $db->updates_test_update = $db->updates_test_update ?? $db->prepare('UPDATE World SET randomNumber = ? WHERE id = ?');
 
 
-    while (0 < $query_count--)
-    {
+    while (0 < $query_count--) {
         $id = mt_rand(1, 10000);
         $id = mt_rand(1, 10000);
         $randomNumber = mt_rand(1, 10000);
         $randomNumber = mt_rand(1, 10000);
-        $ret = $statement->execute(array($id));
+        $ret = $db->updates_test_select->execute([$id]);
 
 
         // Store result in array.
         // Store result in array.
-        $world = array('id' => $id, 'randomNumber' => $ret[0]['randomNumber']);
+        $world = ['id' => $id, 'randomNumber' => $ret[0]['randomNumber']];
         $world['randomNumber'] = $randomNumber;
         $world['randomNumber'] = $randomNumber;
-        $updateStatement->execute(array($randomNumber, $id));
+        $db->updates_test_update->execute([$randomNumber, $id]);
 
 
         $arr[] = $world;
         $arr[] = $world;
     }
     }
@@ -117,71 +125,74 @@ $updates = function ($database_type, $queries = 0) use ($pool) {
 /**
 /**
  * On start of the PHP worker. One worker per server process is started.
  * On start of the PHP worker. One worker per server process is started.
  */
  */
-$server->on('workerStart', function () use (&$pool) {
+$server->on('workerStart', function () use ($pool) {
     $pool->set_host_ip();
     $pool->set_host_ip();
 });
 });
 
 
 /**
 /**
  * On every request to the (web)server, execute the following code
  * On every request to the (web)server, execute the following code
  */
  */
-$server->on('request', function ($req, $res) use ($db, $fortunes, $updates) {
+$server->on('request', function (Request $req, Response $res) use ($db, $fortunes, $updates) {
 
 
-    switch ($req->server['request_uri'])
-    {
-        case "/json":
+    switch ($req->server['request_uri']) {
+        case '/json':
             $res->header('Content-Type', 'application/json');
             $res->header('Content-Type', 'application/json');
-            $res->end(json_encode(array('message' => 'Hello, World!')));
+            $res->end(json_encode(['message' => 'Hello, World!']));
             break;
             break;
 
 
-        case "/plaintext":
+        case '/plaintext':
             $res->header('Content-Type', 'text/plain; charset=utf-8');
             $res->header('Content-Type', 'text/plain; charset=utf-8');
             $res->end('Hello, World!');
             $res->end('Hello, World!');
             break;
             break;
 
 
-        case "/db":
+        case '/db':
             $res->header('Content-Type', 'application/json');
             $res->header('Content-Type', 'application/json');
 
 
-            if (isset($req->get['queries']))
-                $res->end($db("mysql", $req->get['queries']));
-            else
-                $res->end($db("mysql", -1));
+            if (isset($req->get['queries'])) {
+                $res->end($db('mysql', (int)$req->get['queries']));
+            } else {
+                $res->end($db('mysql', -1));
+            }
             break;
             break;
 
 
-        case "/fortunes":
+        case '/fortunes':
             $res->header('Content-Type', 'text/html; charset=utf-8');
             $res->header('Content-Type', 'text/html; charset=utf-8');
-            $res->end($fortunes("mysql"));
+            $res->end($fortunes('mysql'));
             break;
             break;
 
 
-        case "/updates":
+        case '/updates':
             $res->header('Content-Type', 'application/json');
             $res->header('Content-Type', 'application/json');
 
 
-            if (isset($req->get['queries']))
-                $res->end($updates("mysql", $req->get['queries']));
-            else
-                $res->end($updates("mysql", -1));
+            if (isset($req->get['queries'])) {
+                $res->end($updates('mysql', (int)$req->get['queries']));
+            } else {
+                $res->end($updates('mysql', -1));
+            }
             break;
             break;
 
 
-        case "/db_postgres":
+        case '/db_postgres':
             $res->header('Content-Type', 'application/json');
             $res->header('Content-Type', 'application/json');
 
 
-            if (isset($req->get['queries']))
-                $res->end($db("postgres", $req->get['queries']));
-            else
-                $res->end($db("postgres", -1));
+            if (isset($req->get['queries'])) {
+                $res->end($db('postgres', (int)$req->get['queries']));
+            } else {
+                $res->end($db('postgres', -1));
+            }
             break;
             break;
 
 
-        case "/fortunes_postgres":
+        case '/fortunes_postgres':
             $res->header('Content-Type', 'text/html; charset=utf-8');
             $res->header('Content-Type', 'text/html; charset=utf-8');
-            $res->end($fortunes("postgres"));
+            $res->end($fortunes('postgres'));
             break;
             break;
 
 
-        case "/updates_postgres":
+        case '/updates_postgres':
             $res->header('Content-Type', 'application/json');
             $res->header('Content-Type', 'application/json');
 
 
-            if (isset($req->get['queries']))
-                $res->end($updates("postgres", $req->get['queries']));
-            else
-                $res->end($updates("postgres", -1));
+            if (isset($req->get['queries'])) {
+                $res->end($updates('postgres', (int)$req->get['queries']));
+            } else {
+                $res->end($updates('postgres', -1));
+            }
             break;
             break;
     }
     }
 
 
@@ -196,16 +207,16 @@ $server->start();
  */
  */
 class DatabasePool
 class DatabasePool
 {
 {
-    protected $pool;
-    var $pool_count = 0;
-
-    var $server = [
+    private $server = [
         'host' => '',
         'host' => '',
         'user' => 'benchmarkdbuser',
         'user' => 'benchmarkdbuser',
         'password' => 'benchmarkdbpass',
         'password' => 'benchmarkdbpass',
         'database' => 'hello_world'
         'database' => 'hello_world'
     ];
     ];
 
 
+    private $pool;
+    private $pool_count = 0;
+
     function __construct()
     function __construct()
     {
     {
         $this->pool = new \SplQueue;
         $this->pool = new \SplQueue;
@@ -213,8 +224,7 @@ class DatabasePool
 
 
     function set_host_ip()
     function set_host_ip()
     {
     {
-        if (empty($this->server['host']))
-        {
+        if (empty($this->server['host'])) {
             $tfb_database_ip = Swoole\Coroutine::gethostbyname('tfb-database');
             $tfb_database_ip = Swoole\Coroutine::gethostbyname('tfb-database');
             $this->server['host'] = $tfb_database_ip;
             $this->server['host'] = $tfb_database_ip;
         }
         }
@@ -226,25 +236,27 @@ class DatabasePool
         $this->pool_count++;
         $this->pool_count++;
     }
     }
 
 
-    function get($server_type)
+    function get(string $server_type)
     {
     {
-        if ($this->pool_count > 0)
-        {
+        if ($this->pool_count > 0) {
             $this->pool_count--;
             $this->pool_count--;
             return $this->pool->pop();
             return $this->pool->pop();
         }
         }
 
 
         // No idle connection, time to create a new connection
         // No idle connection, time to create a new connection
-        if( $server_type == "mysql" )
+        if ($server_type === 'mysql') {
             $db = new Swoole\Coroutine\Mysql;
             $db = new Swoole\Coroutine\Mysql;
+        }
 
 
-        if( $server_type == "postgres" )
+        if ($server_type === 'postgres') {
             $db = new Swoole\Coroutine\PostgreSql;
             $db = new Swoole\Coroutine\PostgreSql;
+        }
 
 
         $db->connect($this->server);
         $db->connect($this->server);
 
 
-        if ($db == false)
+        if ($db == false) {
             return false;
             return false;
+        }
 
 
         return $db;
         return $db;
     }
     }