public function testExpire() { $key = uniqid(); $c = new FileCache($this->file); $this->assertTrue($c->set($key, ['bar' => ['baz']], 1)); $this->assertEquals(['bar' => ['baz']], $c->get($key)); $this->assertTrue($c->expires($key) <= time() + 1); sleep(2); $this->assertNull($c->get($key)); }
function testSet_expire() { $cache = new FileCache(); $cache->set($this->name, $this->data, new DateTime('-1 day')); $result = $cache->get($this->name); $this->assertSame(null, $result); }
public function __construct() { $http = new swoole_http_server('127.0.0.1', '9999'); $http->set(array('reactor_num' => 1, 'worker_num' => 2, 'backlog' => 128, 'max_request' => 500, 'heartbeat_idle_time' => 30, 'heartbeat_check_interval' => 10, 'dispatch_mode' => 3)); $http->on('request', function ($request, $response) { $request->get = isset($request->get) ? $request->get : []; $request->post = isset($request->post) ? $request->post : []; $request->cookie = isset($request->cookie) ? $request->cookie : []; $request->files = isset($request->files) ? $request->files : []; $request->server = isset($request->server) ? $request->server : []; if ($request->server['request_uri'] == '/favicon.ico') { $response->end(); return; } $cache_dir = \Config::get('cron::cache_dir') ?: 'runtime/cron'; $pid = \FileCache::get('pid', $cache_dir); $work_ids = \FileCache::get('work_ids', $cache_dir); ob_start(); require __DIR__ . "/View/console.php"; $output = ob_get_contents(); ob_end_clean(); $response->status(200); $response->end($output); return; }); $this->http = $http; }
static function get($key) { if (extension_loaded("memcached")) { $memcache = self::memcacheInit(); return $memcache->get($key); } else { return FileCache::get($key); } }
public function init() { $sqlDir = __ROOT__ . "app/sql/"; $lock = \FileCache::isExist("sql.lock", $sqlDir); if ($lock) { $this->fileList = \FileCache::get("sql.lock", $sqlDir); } $this->ListSql($sqlDir); \FileCache::set("sql.lock", $this->fileList, $sqlDir); }
public function init() { $sqlDir = __ROOT__ . "app/sql/"; $lock = \FileCache::isExist("sql.lock", $sqlDir); if ($lock) { $this->fileList = \FileCache::get("sql.lock", $sqlDir); } $this->ListSql($sqlDir); //清除lock $clean = new SqlCleanCommand(); $clean->init(); }
/** * 停止队列服务 * */ public function stop() { $pid = $this->getPid(); if (!empty($pid) && $pid) { if (swoole_process::kill($pid, 0)) { //杀掉worker进程 foreach (\FileCache::get('work_ids', $this->logDir . "/") as $work_id) { swoole_process::kill($work_id, SIGTERM); } } } }
function handle() { $cache = new FileCache(); $info = $cache->get(self::CACHE_KEY); if (!is_array($info)) { $shokos = new VolatileTwitShokos(); $info = $shokos->bestTalkInfo(); $cache->set(self::CACHE_KEY, $info, new DateTime("+30 min")); } $this->assign('rate', $info['rate']); $this->assign('text', $info['text']); $this->assign('status', 'ok'); }
function run() { $cache = new FileCache(); $box = $cache->get(self::TWITTER_CRAWL_KEY); if (!is_array($box)) { $box = array(); } $api = new TwitterApi(HIDETOBARA_OAUTH_KEY, HIDETOBARA_OAUTH_SECRET); $a = $api->getHomeTimeline($box); $storage = new TwitterStorage(); $storage->retrieveStatus($a); $storage->saveStatusByDate(LOG_DIR . "status/"); $box = $storage->updateUserCache($box); $cache->set(self::TWITTER_CRAWL_KEY, $box); }
function search() { $cacheData = FileCache::get('__cache__' . $this->keyword); if (!$cacheData) { $url = $this->queryUrl . urlencode($this->keyword); $request_result = $this->request($url); $json = json_decode($request_result); $searchData = $json->data; if (count($searchData) > 0) { FileCache::set('__cache__' . $this->keyword, $searchData, 24 * 60 * 60); } } else { $searchData = $cacheData; } if (count($searchData) > 0) { $codeArray = array(); foreach ($searchData as $value) { $d = explode('~', $value); if (preg_match('/(\\..*)$/', $d[1], $re)) { $d[1] = str_replace($re[1], "", $d[1]); } if ($d[0] == 'us') { $d[1] = strtoupper($d[1]); } $dCode = $d[0] . $d[1]; if ($d[0] == 'hk') { $dCode = 'r_' . $dCode; } if ($d[0] == 'jj') { $dCode = 's_' . $dCode; } array_push($codeArray, $dCode); } $qt = new StockQt(); $qt->fetchQt(implode(',', $codeArray)); foreach ($searchData as $key => $value) { $stock = new Stock($value, $qt); $this->result($key, $stock->getLink(), $stock->getTitle(), $stock->getSubTitle(), null); } } else { $this->lastPlaceholder(); } }
function search() { $qtData = FileCache::get($this->keyword); if (!$qtData) { $url = $this->queryUrl . urlencode($this->keyword); $request_result = $this->request($url); $json = json_decode($request_result); $qtData = $json->data; } if (count($qtData) > 0) { FileCache::set($this->keyword, $qtData); foreach ($qtData as $key => $value) { $stock = new Stock($value); $this->result($key, $stock->getLink(), $stock->getTitle(), $stock->getSubTitle(), null); } } else { $this->lastPlaceholder(); } }
private function content_key_for_mtime_key($key, $work_units) { if (!(defined('SACY_USE_CONTENT_BASED_CACHE') && SACY_USE_CONTENT_BASED_CACHE)) { return $key; } $cache_key = 'ck-for-mkey-' . $key; $ck = $this->fragment_cache->get($cache_key); if (!$ck) { $ck = ""; foreach ($work_units as $f) { $ck = md5($ck . md5_file($f['file'])); foreach ($f['additional_files'] as $af) { $ck = md5($ck . md5_file($af)); } } $ck = "{$ck}-content"; $this->fragment_cache->set($cache_key, $ck); } return $ck; }
<?php require_once "../../phplib/util.php"; util_assertNotMirror(); util_assertNotLoggedIn(); $loginType = util_getRequestParameter('loginType'); $nickOrEmail = util_getRequestParameter('nickOrEmail'); $password = util_getRequestParameter('password'); $nick = util_getRequestParameter('nick'); $randString = util_getRequestParameter('randString'); $data = FileCache::get($randString); if (!$data) { FlashMessage::add('A apărut o eroare la autentificare. Vă rugăm încercați din nou.'); } else { if ($loginType == 0) { $user = Model::factory('User')->where('password', md5($password))->where_raw("(email = '{$nickOrEmail}' or nick = '{$nickOrEmail}')")->find_one(); if (!$user) { FlashMessage::add('Numele de utilizator sau parola sunt incorecte.'); } else { if ($user->identity) { FlashMessage::add('Acest utilizator a fost deja revendicat de un alt OpenID.'); } else { session_login($user, $data); } } } else { $openidNick = $loginType == 1 ? $data['fullname'] : ($loginType == 2 ? $data['nickname'] : $nick); $user = User::get_by_nick($openidNick); if ($user) { FlashMessage::add('Acest nume de utilizator este deja luat.'); } else {
<?php require_once "../../phplib/util.php"; util_assertNotMirror(); util_assertNotLoggedIn(); $token = util_getRequestParameter('token'); $identity = util_getRequestParameter('identity'); $pt = PasswordToken::get_by_token($token); $data = FileCache::get($identity); if (!$pt) { FlashMessage::add('Ați introdus un cod de recuperare incorect.'); } else { if ($pt->createDate < time() - 24 * 3600) { FlashMessage::add('Codul de recuperare introdus a expirat.'); } else { if (!$data) { FlashMessage::add('Ați introdus o identitate incorectă.'); } else { $user = User::get_by_id($pt->userId); if (!$user) { FlashMessage::add('Ați introdus un cod de recuperare incorect.'); } else { if ($user->identity) { FlashMessage::add('Acest cont a fost deja revendicat de o identitate OpenID.'); } else { FlashMessage::add('Contul dumneavoastră a fost recuperat și unificat cu identitatea OpenID.', 'info'); session_login($user, $data); } } } }
private function getRoutingConfig() { $file = 'route/routing.php'; if ($this->container->getEnvironment() == "prod") { if (\FileCache::isExist($file)) { return \FileCache::get($file); } } $sources = \Config::get('routing::source'); $routings = []; foreach ($sources as $source) { $routing = (include_once "src/{$source}/routing.php"); if ($routing) { $routings = array_merge($routings, $routing); } } \FileCache::set($file, $routings); return $routings; }
private function getMethodsCache() { $file = 'route/routing_' . $this->route->getCurrentMethod() . '.php'; if (\FileCache::isExist($file)) { return \FileCache::get($file); } $config = $this->createMethodsCache(); \FileCache::set($file, $config); return $config; }
$json_options['B'][] = $entity; } $redirect = true; } if ($redirect) { $json = urlencode(json_encode($json_options)); $url = "/related/{$systemID}/{$relatedTime}/o/{$json}/"; $app->redirect($url, 302); die; } $systemInfo = $mdb->findDoc('information', ['cacheTime' => 3600, 'type' => 'solarSystemID', 'id' => $systemID]); $systemName = $systemInfo['name']; $regionInfo = $mdb->findDoc('information', ['cacheTime' => 3600, 'type' => 'regionID', 'id' => $systemInfo['regionID']]); $regionName = $regionInfo['name']; $unixTime = strtotime($relatedTime); $time = date('Y-m-d H:i', $unixTime); $exHours = 1; if ((int) $exHours < 1 || (int) $exHours > 12) { $exHours = 1; } $key = "{$systemID}:{$relatedTime}:{$exHours}:" . json_encode($json_options); $cache = new FileCache($baseDir . '/cache/related/'); $mc = $cache->get($key); if (!$mc) { $parameters = array('solarSystemID' => $systemID, 'relatedTime' => $relatedTime, 'exHours' => $exHours); $kills = Kills::getKills($parameters); $summary = Related::buildSummary($kills, $parameters, $json_options); $mc = array('summary' => $summary, 'systemName' => $systemName, 'regionName' => $regionName, 'time' => $time, 'exHours' => $exHours, 'solarSystemID' => $systemID, 'relatedTime' => $relatedTime, 'options' => json_encode($json_options)); $cache->set($key, $mc, 600); } $app->render('related.html', $mc);
$staticCache = new FileCache(ROOT . '/tmp/cache/static'); $cspCache = new FileCache(ROOT . '/tmp/cache/csp_static'); } $port = $_SERVER['HTTP_PORT'] ?? ''; $lookup = $_SERVER['HTTP_HOST'] . ':' . $port . '/' . $_SERVER['REQUEST_URI']; $staticPage = $staticCache->get($lookup); if (!empty($staticPage)) { if (!\headers_sent()) { \header('Content-Type: text/html;charset=UTF-8'); \header('Content-Language: ' . $state->lang); \header('X-Content-Type-Options: nosniff'); \header('X-Frame-Options: SAMEORIGIN'); // Maybe make this configurable down the line? \header('X-XSS-Protection: 1; mode=block'); } $csp = $cspCache->get($lookup); if (!empty($csp)) { foreach (\json_decode($csp, true) as $cspHeader) { \header($cspHeader); } } echo $staticPage; // This is just for benchmarking purposes: echo '<!-- Load time: ' . \round(\microtime(true) - $start, 5) . ' s (static page) -->'; exit; } unset($staticCache); } // Load all of the prerequisites: require_once ROOT . '/bootstrap.php'; /**
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ define('ROOT', substr(dirname(__FILE__), 0, -12)); //以/结尾 require_once ROOT . 'include/lib/FileCache.class.php'; $key = isset($_GET['key']) ? trim($_GET['key']) : ''; $cache = new FileCache(); $cache->cachePath = ROOT . 'data/cache/'; //$data = $cache->get('yourkey'); if ($key == 'categories') { $categories = ''; $data = $cache->get('categories'); if (count($data[0]) > 0) { foreach ($data[0] as $val) { $categories .= "<li><a href=\"/category/{$val->slug}/\">{$val->name}</a> <small>({$val->count})</small></li>\n"; } } echo $categories; } if ($key == 'hot_tags') { $hot_tags = ''; $data = $cache->get('hot_tags'); if (count($data) > 0) { foreach ($data as $val) { $hot_tags .= "<li><a href=\"/tag/{$val->name}/\">{$val->name}</a></li>\n"; } }
clearstatcache(); $filesize = filesize($filename); if ($filesize > 0) { $data = fread($fp, $filesize); } flock($fp, LOCK_UN); fclose($fp); return $data; } else { return false; } } } //例子 $cache = new FileCache(); $data = $cache->get('yourkey'); //yourkey是你为每一个要缓存的数据定义的缓存名字 if ($data === false) { $data = '从数据库取出的数据或很复杂很耗时的弄出来的数据'; $cache->set('yourkey', $data, 3600); //缓存3600秒 } // use your $data /* 看代码 例子解释 一开始你从缓存中取数据(get)如果数据有缓存就直接使用缓存中的数据了。 如果缓存过期或没有,那重新取数据(数据库或其它),然后保存到缓存中。再使用你的数据。
/** * @param int $account_id * @param bool $only_cached If true then only cached response will be retrieved * @param int $cache_validity_in_minutes Provide 0 or false to force request * * @return array|null * @throws Exception */ public static function get_unread_messages($account_id, $only_cached = false, $cache_validity_in_minutes = 3) { $return = null; $rec = Utils_RecordBrowserCommon::get_record('rc_accounts', $account_id); if ($rec['epesi_user'] !== Acl::get_user()) { throw new Exception('Invalid account id'); } $port = $rec['security'] == 'ssl' ? 993 : 143; $server_str = '{' . $rec['server'] . '/imap/readonly/novalidate-cert' . ($rec['security'] ? '/' . $rec['security'] : '') . ':' . $port . '}'; $cache_key = md5($server_str . ' # ' . $rec['login'] . ' # ' . $rec['password']); $cache = new FileCache(DATA_DIR . '/cache/roundcube_unread.php'); if ($cache_validity_in_minutes) { $unread_messages = $cache->get($cache_key); if ($unread_messages && ($only_cached || $unread_messages['t'] > time() - $cache_validity_in_minutes * 60)) { $return = $unread_messages['val']; } } if ($return === null && $only_cached === false) { @set_time_limit(0); $mailbox = @imap_open(imap_utf7_encode($server_str), imap_utf7_encode($rec['login']), imap_utf7_encode($rec['password']), OP_READONLY || OP_SILENT); $err = imap_errors(); $unseen = array(); if (!$mailbox || $err) { $err = __('Connection error') . ": " . implode(', ', $err); } else { $uns = @imap_search($mailbox, 'UNSEEN ALL'); if ($uns) { $l = @imap_fetch_overview($mailbox, implode(',', $uns), 0); $err = imap_errors(); if (!$l || $err) { $error_info = $err ? ": " . implode(', ', $err) : ""; $err = __('Error reading messages overview') . $error_info; } else { foreach ($l as $msg) { $from = isset($msg->from) ? imap_utf8($msg->from) : '<unknown>'; $subject = isset($msg->subject) ? imap_utf8($msg->subject) : '<no subject>'; $date = isset($msg->date) ? $msg->date : ''; $unseen[] = array('from' => $from, 'subject' => $subject, 'id' => $msg->uid, 'date' => $date, 'unix_timestamp' => $msg->udate); } } } } if (!is_bool($mailbox)) { imap_close($mailbox); } imap_errors(); // called just to clean up errors. if ($err) { throw new Exception($err); } else { $return = $unseen; $cache->set($cache_key, array('val' => $return, 't' => time())); } } return $return; }
<?php error_reporting(8191); require_once 'class/IInterface.php'; require_once 'class/FileCacheAbstract.php'; require_once 'class/FileCache.php'; $expire = 10; // sec $cache = new FileCache('/cache'); // only as example do not set dir in real life! if ($content = $cache->get('main')) { echo 'This Page from cache for ' . $cache->getRemainigCacheTimeByKey('main') . ' sec!<br>'; echo $content; exit; } $cache->startCaching(); $param = 'This is main page'; echo '<h1>Main Page</h1>'; echo '<p>' . $param . '</p>'; $cache->put('main', $cache->getCacheContent(), $expire); header('Content-Type: text/html; charset=utf-8'); $cache->stopAndShowCaching(); exit;
/** * This initialize those include path. * */ public static function initialize() { //this is set for FileCache usage $root = PathService::getRootDir(); $configFile = $root . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "config.ini"; if (file_exists($configFile)) { set_include_path(get_include_path() . PATH_SEPARATOR . "app" . DIRECTORY_SEPARATOR . "library" . DIRECTORY_SEPARATOR . "cache"); if (!is_null(FileCache::get(self::FILECACHE))) { set_include_path(FileCache::get(self::FILECACHE)); return; } } set_include_path(get_include_path() . PATH_SEPARATOR . "core"); set_include_path(get_include_path() . PATH_SEPARATOR . "config"); set_include_path(get_include_path() . PATH_SEPARATOR . "app"); set_include_path(get_include_path() . PATH_SEPARATOR . "app" . DIRECTORY_SEPARATOR . "library"); set_include_path(get_include_path() . PATH_SEPARATOR . "project"); set_include_path(get_include_path() . PATH_SEPARATOR . "project" . DIRECTORY_SEPARATOR . "share"); set_include_path(get_include_path() . PATH_SEPARATOR . "project" . DIRECTORY_SEPARATOR . "modules"); set_include_path(get_include_path() . PATH_SEPARATOR . "plugin"); //set module paths $modulePath = $root . DIRECTORY_SEPARATOR . "project" . DIRECTORY_SEPARATOR . "modules"; $moduleFolders = Initializer::getDirectory($modulePath, TRUE); foreach ($moduleFolders as $i => $mfolder) { $fd = trim($mfolder); $rp = trim($modulePath) . DIRECTORY_SEPARATOR; $f = "modules" . DIRECTORY_SEPARATOR . str_replace($rp, "", $fd); set_include_path(get_include_path() . PATH_SEPARATOR . $f); } /** * include folders under project, library, plug-in * */ $plugIn = $root . DIRECTORY_SEPARATOR . "plugin"; $coreLib = $root . DIRECTORY_SEPARATOR . "app" . DIRECTORY_SEPARATOR . "library"; $project = $root . DIRECTORY_SEPARATOR . "project"; $plugInFolders = Initializer::getDirectory($plugIn, TRUE); foreach ($plugInFolders as $i => $folder1) { $fd = trim($folder1); $rp = trim($plugIn) . DIRECTORY_SEPARATOR; $f = "plugin" . DIRECTORY_SEPARATOR . str_replace($rp, "", $fd); set_include_path(get_include_path() . PATH_SEPARATOR . $f); } $coreLibFolders = Initializer::getDirectory($coreLib, TRUE); foreach ($coreLibFolders as $i => $folder1) { $fd = trim($folder1); $rp = trim($coreLib) . DIRECTORY_SEPARATOR; $f = "app" . DIRECTORY_SEPARATOR . "library" . DIRECTORY_SEPARATOR . str_replace($rp, "", $fd); set_include_path(get_include_path() . PATH_SEPARATOR . $f); } $projectFolders = Initializer::getDirectory($project, TRUE); foreach ($projectFolders as $i => $folder1) { $fd = trim($folder1); $rp = trim($project) . DIRECTORY_SEPARATOR; $f = "project" . DIRECTORY_SEPARATOR . str_replace($rp, "", $fd); set_include_path(get_include_path() . PATH_SEPARATOR . $f); } if (file_exists($configFile)) { FileCache::save(self::FILECACHE, get_include_path()); } }