Exemple #1
0
 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);
 }
Exemple #2
0
 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));
 }
 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);
 }
Exemple #4
0
 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);
 }
Exemple #6
0
 public function blindClass()
 {
     opcache_reset();
     $loader = (require __ROOT__ . '/vendor/autoload.php');
     $loader->setUseIncludePath(true);
     $app = new \Group\App\App();
     $app->initSelf();
     $app->doBootstrap($loader);
     $app->registerServices();
     $app->singleton('container')->setAppPath(__ROOT__);
     $classMap = new Group\Common\ClassMap();
     $classes = $classMap->doSearch();
     \FileCache::set('services', $classes, $this->cacheDir);
     $this->addClass($classes, $this->server);
 }
Exemple #7
0
 /**
  * 检查输入的参数与命令
  *
  */
 protected function checkArgv()
 {
     $argv = $this->argv;
     if (!isset($argv[1])) {
         return;
     }
     $config = \Config::get("async::server");
     if (!isset($config[$argv[1]])) {
         return;
     }
     $log = isset($config[$argv[1]]['config']['log_file']) ? $config[$argv[1]]['config']['log_file'] : 'runtime/async/default.log';
     $log = explode("/", $log);
     \FileCache::set(array_pop($log), '', implode("/", $log) . "/");
     $server = new Server($config[$argv[1]], $argv[1]);
     die;
 }
 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();
     }
 }
Exemple #9
0
 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();
     }
 }
            }
            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)如果数据有缓存就直接使用缓存中的数据了。

如果缓存过期或没有,那重新取数据(数据库或其它),然后保存到缓存中。再使用你的数据。


我们可以这样想,这个页面第一次被访问的时候,是取不到缓存数据的所以$data是false,这时按正常逻辑取数据。
Exemple #11
0
 /**
  * 设置worker进程的pid
  *
  * @param pid int
  */
 private function setWorkerPids($pid)
 {
     $this->workerPids[] = $pid;
     \FileCache::set('work_ids', $this->workerPids, $this->logDir . "/");
 }
Exemple #12
0
        $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);
Exemple #13
0
 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;
 }
Exemple #14
0
 /**
  * @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;
 }
Exemple #15
0
 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;
 }
Exemple #16
0
 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;
 }