Authored by wuxiao

ShmCache.php

... ... @@ -35,14 +35,24 @@ class Parser{
static $self;
if (empty($self)){
$self = new self;
//初始化缓存句柄
if (function_exists('apcu_store')){
$self->cache = Yii::createObject([
'class'=>'yii\caching\ApcCache',
'useApcu'=>true
]);
}elseif (function_exists('apc_store')){
$self->cache = Yii::createObject('yii\caching\ApcCache');
}elseif (function_exists('shm_attach')){
$self->cache = Yii::createObject('common\components\caching\ShmCache');
}else{
$self->cache = Yii::createObject('yii\caching\ArrayCache');
}
}
return $self;
}
public function __construct() {
$this->cache = Yii::createObject('yii\caching\ArrayCache');
}
/**
* 载入路径
* @param type $path
... ...
<?php
namespace common\components\caching;
use yii\caching\Cache;
use yii\base\InvalidConfigException;
class ShmCache extends Cache
{
//memory size bytes,default 10MB
public $memSize = 10485760;
protected $shm;
/**
* Initializes this application component.
* It checks if extension required is loaded.
*/
public function init()
{
parent::init();
if (!extension_loaded('sysvshm')) {
throw new InvalidConfigException("ShmCache requires PHP sysvshm extension to be loaded.");
}
$key = ftok(__FILE__, 'p');
$this->shm = shm_attach($key,10000);
}
public function exists($key)
{
$key = $this->buildKey($key);
return shm_has_var($this->shm,$key);
}
protected function getValue($key)
{
return @shm_get_var($this->shm,$key);
}
protected function getValues($keys)
{
$results = [];
foreach ($keys as $key) {
$results[$key] = @shm_get_var($this->shm,$key);
}
return $results;
}
protected function setValue($key, $value, $duration)
{
return shm_put_var($this->shm,$key,$value);
}
protected function addValue($key, $value, $duration)
{
return shm_has_var($this->shm,$key) ? false : shm_put_var($this->shm,$key,$value);
}
protected function deleteValue($key)
{
return @shm_remove_var($this->shm,$key);
}
protected function flushValues()
{
return shm_remove($this->shm);
}
public function buildKey($key)
{
return crc32(parent::buildKey($key));
}
}
... ...