From 75c901a111566b6e74b09a3c267c3d578142888d Mon Sep 17 00:00:00 2001 From: jokob-sk Date: Fri, 5 Aug 2022 15:26:28 +1000 Subject: [PATCH] Optimisation no 4: cache device totals for 5min --- front/php/server/devices.php | 56 +++++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/front/php/server/devices.php b/front/php/server/devices.php index 9600a225..a45f587e 100644 --- a/front/php/server/devices.php +++ b/front/php/server/devices.php @@ -478,22 +478,35 @@ function PiaToggleArpScan() { // Query total numbers of Devices by status //------------------------------------------------------------------------------ function getDevicesTotals() { - global $db; - // combined query - $result = $db->query( - 'SELECT - (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('all').') as devices, - (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('connected').') as connected, - (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('favorites').') as favorites, - (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('new').') as new, - (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('down').') as down, - (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('archived').') as archived - '); + $resultJSON = ""; - $row = $result -> fetchArray (SQLITE3_NUM); + if(getCache("getDevicesTotals") != "") + { + $resultJSON = getCache("getDevicesTotals"); + } else + { + global $db; - echo (json_encode (array ($row[0], $row[1], $row[2], $row[3], $row[4], $row[5]))); + // combined query + $result = $db->query( + 'SELECT + (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('all').') as devices, + (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('connected').') as connected, + (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('favorites').') as favorites, + (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('new').') as new, + (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('down').') as down, + (SELECT COUNT(*) FROM Devices '. getDeviceCondition ('archived').') as archived + '); + + $row = $result -> fetchArray (SQLITE3_NUM); + $resultJSON = json_encode (array ($row[0], $row[1], $row[2], $row[3], $row[4], $row[5])); + + // save to cache + setCache("getDevicesTotals", $resultJSON ); + } + + echo ($resultJSON); } @@ -798,4 +811,21 @@ function getDeviceCondition ($deviceStatus) { } } +//------------------------------------------------------------------------------ +// Simple cookie cache +//------------------------------------------------------------------------------ +function getCache($key) { + if( isset($_COOKIE[$key])) + { + return $_COOKIE[$key]; + }else + { + return ""; + } +} + +function setCache($key, $value) { + setcookie($key, $value, time()+300, "/","", 0); // 5min cache +} + ?>