Authored by wuxiao

ShmCache.php

@@ -35,14 +35,24 @@ class Parser{ @@ -35,14 +35,24 @@ class Parser{
35 static $self; 35 static $self;
36 if (empty($self)){ 36 if (empty($self)){
37 $self = new self; 37 $self = new self;
  38 +
  39 + //初始化缓存句柄
  40 + if (function_exists('apcu_store')){
  41 + $self->cache = Yii::createObject([
  42 + 'class'=>'yii\caching\ApcCache',
  43 + 'useApcu'=>true
  44 + ]);
  45 + }elseif (function_exists('apc_store')){
  46 + $self->cache = Yii::createObject('yii\caching\ApcCache');
  47 + }elseif (function_exists('shm_attach')){
  48 + $self->cache = Yii::createObject('common\components\caching\ShmCache');
  49 + }else{
  50 + $self->cache = Yii::createObject('yii\caching\ArrayCache');
  51 + }
38 } 52 }
39 return $self; 53 return $self;
40 } 54 }
41 55
42 - public function __construct() {  
43 - $this->cache = Yii::createObject('yii\caching\ArrayCache');  
44 - }  
45 -  
46 /** 56 /**
47 * 载入路径 57 * 载入路径
48 * @param type $path 58 * @param type $path
  1 +<?php
  2 +
  3 +namespace common\components\caching;
  4 +
  5 +use yii\caching\Cache;
  6 +use yii\base\InvalidConfigException;
  7 +
  8 +class ShmCache extends Cache
  9 +{
  10 +
  11 + //memory size bytes,default 10MB
  12 + public $memSize = 10485760;
  13 +
  14 + protected $shm;
  15 +
  16 + /**
  17 + * Initializes this application component.
  18 + * It checks if extension required is loaded.
  19 + */
  20 + public function init()
  21 + {
  22 + parent::init();
  23 + if (!extension_loaded('sysvshm')) {
  24 + throw new InvalidConfigException("ShmCache requires PHP sysvshm extension to be loaded.");
  25 + }
  26 +
  27 + $key = ftok(__FILE__, 'p');
  28 + $this->shm = shm_attach($key,10000);
  29 + }
  30 +
  31 + public function exists($key)
  32 + {
  33 + $key = $this->buildKey($key);
  34 +
  35 + return shm_has_var($this->shm,$key);
  36 + }
  37 +
  38 + protected function getValue($key)
  39 + {
  40 + return @shm_get_var($this->shm,$key);
  41 + }
  42 +
  43 + protected function getValues($keys)
  44 + {
  45 + $results = [];
  46 + foreach ($keys as $key) {
  47 + $results[$key] = @shm_get_var($this->shm,$key);
  48 + }
  49 + return $results;
  50 + }
  51 +
  52 + protected function setValue($key, $value, $duration)
  53 + {
  54 + return shm_put_var($this->shm,$key,$value);
  55 + }
  56 +
  57 + protected function addValue($key, $value, $duration)
  58 + {
  59 + return shm_has_var($this->shm,$key) ? false : shm_put_var($this->shm,$key,$value);
  60 + }
  61 +
  62 + protected function deleteValue($key)
  63 + {
  64 + return @shm_remove_var($this->shm,$key);
  65 + }
  66 +
  67 + protected function flushValues()
  68 + {
  69 + return shm_remove($this->shm);
  70 + }
  71 +
  72 + public function buildKey($key)
  73 + {
  74 + return crc32(parent::buildKey($key));
  75 + }
  76 +}