Ejemplo n.º 1
0
 public function set(string $key, string $value, int $life = 3600) : bool
 {
     if ($life == 0) {
         $life = null;
     }
     return apcu_add($key, $value, $life);
 }
Ejemplo n.º 2
0
 public function cacheData($key, $data, $timeCache = null)
 {
     if (apcu_exists($key)) {
         return apcu_fetch($key, false);
     } else {
         if (!empty($timeCache)) {
             apcu_add($key, $data, $timeCache);
         } else {
             apcu_add($key, $data, $this->timeCache);
         }
     }
 }
Ejemplo n.º 3
0
 /**
  * {@inheritdoc}
  *
  * @return \Orno\Cache\Adapter\Apc
  */
 public function set($key, $data, $expiry = null)
 {
     if (is_null($expiry)) {
         $expiry = $this->getExpiry();
     }
     if (is_string($expiry)) {
         $expiry = $this->convertExpiryString($expiry);
     }
     if ($this->apcu) {
         apcu_add($key, $data, $expiry);
     } else {
         apc_add($key, $data, $expiry);
     }
     return $this;
 }
Ejemplo n.º 4
0
 public function __construct($namespace = '', $defaultLifetime = 0, $version = null)
 {
     if (!static::isSupported()) {
         throw new CacheException('APCu is not enabled');
     }
     if ('cli' === PHP_SAPI) {
         ini_set('apc.use_request_time', 0);
     }
     parent::__construct($namespace, $defaultLifetime);
     if (null !== $version) {
         CacheItem::validateKey($version);
         if (!apcu_exists($version . ':' . $namespace)) {
             $this->clear($namespace);
             apcu_add($version . ':' . $namespace, null);
         }
     }
 }
Ejemplo n.º 5
0
 public function addVote(Request $request)
 {
     $object = $this->getObject($request->get('id'), $request->get('type'));
     if (!$object) {
         return response()->make('Object not found', 404);
     }
     if ($this->getVoteElement($object, Auth::user())) {
         return response()->make('Already voted', 400);
     }
     if ($object->user->getKey() == Auth::id()) {
         return response()->make('Do not cheat', 400);
     }
     if ($object instanceof ContentRelated) {
         $group = $object->content->group;
     } else {
         $group = $object->group;
     }
     if (Auth::user()->isBanned($group)) {
         return response()->make('Banned', 400);
     }
     if (!apcu_add('anti_vote_flood.user.' . Auth::id(), 1, 1)) {
         return response()->make('Don\'t flood', 400);
     }
     $uv = $object->uv;
     $dv = $object->dv;
     $up = request('up') === 'true';
     if ($up) {
         $object->increment('uv');
         $object->increment('score');
         // small hack, as increment function doesn't update object :(
         $uv++;
         // small trigger, needed for pushing contents to front page
         if ($object instanceof Content && !$object->frontpage_at && $object->uv > config('strimoid.homepage.threshold') && $object->created_at->diffInDays() < config('strimoid.homepage.time_limit')) {
             $object->frontpage_at = new Carbon();
             $object->save();
         }
     } else {
         $object->increment('dv');
         $object->decrement('score');
         $dv++;
     }
     $object->votes()->create(['created_at' => new Carbon(), 'user_id' => Auth::id(), 'up' => $up]);
     return response()->json(['status' => 'ok', 'uv' => $uv, 'dv' => $dv]);
 }
Ejemplo n.º 6
0
 public function testApcu()
 {
     $key = __CLASS__;
     apcu_delete($key);
     $this->assertFalse(apcu_exists($key));
     $this->assertTrue(apcu_add($key, 123));
     $this->assertTrue(apcu_exists($key));
     $this->assertSame(array($key => -1), apcu_add(array($key => 123)));
     $this->assertSame(123, apcu_fetch($key));
     $this->assertTrue(apcu_store($key, 124));
     $this->assertSame(124, apcu_fetch($key));
     $this->assertSame(125, apcu_inc($key));
     $this->assertSame(124, apcu_dec($key));
     $this->assertTrue(apcu_cas($key, 124, 123));
     $this->assertFalse(apcu_cas($key, 124, 123));
     $this->assertTrue(apcu_delete($key));
     $this->assertFalse(apcu_delete($key));
     $this->assertArrayHasKey('cache_list', apcu_cache_info());
 }
Ejemplo n.º 7
0
 function cache_Create($key, $value = null, $ttl = 0)
 {
     global $CACHE_STORE_COUNT;
     $CACHE_STORE_COUNT++;
     return apcu_add($key, $value, $ttl);
 }
Ejemplo n.º 8
0
 /**
  * {@inheritdoc}
  */
 public function add($key, $value, $ttl = 0)
 {
     $res = apcu_add($key, $value, $ttl);
     return $res;
 }
Ejemplo n.º 9
0
 /**
  * Lock cached item
  *
  * @param   string   $key The cache data key
  * @param   string   $group The cache data group
  * @param   integer  $locktime Cached item max lock time
  *
  * @return  boolean
  *
  * @since   1.2.7
  */
 public function lock($key, $group, $locktime)
 {
     $output = array();
     $output['waited'] = false;
     $looptime = $locktime * 10;
     $cache_key = $this->_getCacheId($key, $group) . '_lock';
     $data_lock = apcu_add($cache_key, 1, $locktime);
     if ($data_lock === false) {
         $lock_counter = 0;
         // Loop until you find that the lock has been released. That implies that data get from other thread has finished
         while ($data_lock === false) {
             if ($lock_counter > $looptime) {
                 $output['locked'] = false;
                 $output['waited'] = true;
                 break;
             }
             usleep(100);
             $data_lock = apcu_add($cache_key, 1, $locktime);
             $lock_counter++;
         }
     }
     $output['locked'] = $data_lock;
     return $output;
 }
Ejemplo n.º 10
0
 /**
  * @param string|string[] $key
  * @param mixed           $var
  * @param int             $ttl
  *
  * @return bool|bool[]
  */
 protected function apcu_add($key, $var, $ttl = 0)
 {
     if (function_exists('apcu_add')) {
         return apcu_add($key, $var, $ttl);
     } else {
         return apc_add($key, $var, $ttl);
     }
 }
Ejemplo n.º 11
0
 /**
  * Try to cache the callback result in APCU
  * @param type $name
  * @param \Blend\Component\Cache\callable $callback
  * @return mixed
  */
 private function withMemory($name, callable $callback)
 {
     if (apcu_exists($name)) {
         $success = false;
         $result = apcu_fetch($name, $success);
         if ($success) {
             return $result;
         } else {
             $this->logger->warning('APCU cache did not return correctly!', ['cache' => $name]);
             return call_user_func($callback);
         }
     } else {
         $result = call_user_func($callback);
         if (!apcu_add($name, $result)) {
             $this->logger->warning("Unable to store data in cache!", ['data' => $result]);
         }
         return $result;
     }
 }
Ejemplo n.º 12
0
 public function add($key, $value, $seconds = 0)
 {
     $key = $this->prefix . $key;
     return $this->apcu ? apcu_add($key, $value, $seconds) : apc_add($key, $value, $seconds);
 }
Ejemplo n.º 13
0
 /**
  * Internal method to decrement an item.
  *
  * @param  string $normalizedKey
  * @param  int    $value
  * @return int|bool The new value on success, false on failure
  * @throws Exception\ExceptionInterface
  */
 protected function internalDecrementItem(&$normalizedKey, &$value)
 {
     $options = $this->getOptions();
     $namespace = $options->getNamespace();
     $prefix = $namespace === '' ? '' : $namespace . $options->getNamespaceSeparator();
     $internalKey = $prefix . $normalizedKey;
     $value = (int) $value;
     $newValue = apcu_dec($internalKey, $value);
     // initial value
     if ($newValue === false) {
         $ttl = $options->getTtl();
         $newValue = -$value;
         if (!apcu_add($internalKey, $newValue, $ttl)) {
             throw new Exception\RuntimeException("apcu_add('{$internalKey}', {$newValue}, {$ttl}) failed");
         }
     }
     return $newValue;
 }
Ejemplo n.º 14
0
 /**
  * Adds multiple key-value pairs to cache.
  * @param array $data array where key corresponds to cache key while value is the value stored
  * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  * @return array array of failed keys
  */
 protected function addValues($data, $duration)
 {
     $result = $this->useApcu ? apcu_add($data, null, $duration) : apc_add($data, null, $duration);
     return is_array($result) ? array_keys($result) : [];
 }
Ejemplo n.º 15
0
 function apc_add($key, $var, $ttl = 0)
 {
     return apcu_add($key, $var, $ttl);
 }
Ejemplo n.º 16
0
 /**
  * Acquires a lock on the given key for the given identifier.
  *
  * @param string $key The key we are locking.
  * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
  *      The use of this property is entirely optional and implementations can act as they like upon it.
  * @return bool True if the lock could be acquired, false otherwise.
  */
 public function acquire_lock($key, $ownerid)
 {
     return apcu_add($this->prepare_lock($key), $ownerid);
 }
Ejemplo n.º 17
0
 public function apcu_set()
 {
     $val = "hello world!";
     $res = apcu_add($this->key, $val);
     return TRUE === $res ? 'had cached' : 'cache fail';
 }
Ejemplo n.º 18
0
 /**
  * Adds a value to the shared memory storage.
  *
  * Adds a value to the storage if it doesn't exist, or fails if it does.
  *
  * @param string $key   Name of key to associate the value with.
  * @param mixed  $value Value for the specified key.
  * @param int    $ttl   Seconds to store the value. If set to 0 indicates no
  *     time limit.
  *
  * @return bool TRUE on success, FALSE on failure.
  */
 public function add($key, $value, $ttl = 0)
 {
     return apcu_add($this->persistentId . 'd ' . $key, $value, $ttl);
 }
Ejemplo n.º 19
0
 /**
  * Finds the path to the file where the class is defined.
  *
  * @param string $class The name of the class
  *
  * @return string|false The path if found, false otherwise
  */
 public function findFile($class)
 {
     // class map lookup
     if (isset($this->classMap[$class])) {
         return $this->classMap[$class];
     }
     if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
         return false;
     }
     if (null !== $this->apcuPrefix) {
         $file = apcu_fetch($this->apcuPrefix . $class, $hit);
         if ($hit) {
             return $file;
         }
     }
     $file = $this->findFileWithExtension($class, '.php');
     // Search for Hack files if we are running on HHVM
     if (false === $file && defined('HHVM_VERSION')) {
         $file = $this->findFileWithExtension($class, '.hh');
     }
     if (null !== $this->apcuPrefix) {
         apcu_add($this->apcuPrefix . $class, $file);
     }
     if (false === $file) {
         // Remember that this class does not exist.
         $this->missingClasses[$class] = true;
     }
     return $file;
 }
Ejemplo n.º 20
0
 /**
  * Set a cache entry
  *
  * @param string $key
  * @param $value
  * @return mixed
  */
 public function set(string $key, $value) : bool
 {
     // We will NOT use unserialize here.
     $value = \json_encode($value);
     if (!$value) {
         return false;
     }
     if ($this->authKey) {
         // We're authenticating this value:
         $mac = Symmetric::authenticate($value, $this->authKey, true);
         $value = $mac . $value;
     }
     $shmKey = $this->getSHMKey($key);
     return \apcu_add($shmKey, $value);
 }
Ejemplo n.º 21
0
 public static function add($cacheId, $data, $ttl = null)
 {
     if (self::getBackend() == 'memcache') {
         return self::getMemcache()->set(self::_getMemcachePrefix() . md5($cacheId), $data, 0, $ttl);
     } else {
         if (self::getBackend() == 'redis') {
             if (!$ttl) {
                 $ttl = 365 * 24 * 60 * 60;
             }
             //Set a TTL so it can be evicted http://stackoverflow.com/questions/16370278/how-to-make-redis-choose-lru-eviction-policy-for-only-some-of-the-keys
             $ret = self::getRedis()->setEx('simple:' . self::$namespace . ':' . $cacheId, $ttl, serialize($data));
             return $ret;
         } else {
             if (self::getBackend() == 'apc') {
                 static $prefix;
                 if (!isset($prefix)) {
                     $prefix = self::$uniquePrefix . '-';
                 }
                 return apc_add($prefix . $cacheId, $data, $ttl);
             } else {
                 if (self::getBackend() == 'apcu') {
                     static $prefix;
                     if (!isset($prefix)) {
                         $prefix = self::$uniquePrefix . '-';
                     }
                     return apcu_add($prefix . $cacheId, $data, $ttl);
                 } else {
                     if (self::getBackend() == 'file') {
                         $file = self::_getFileNameForCacheId($cacheId);
                         $data = array($data);
                         if ($ttl) {
                             $data[1] = time() + $ttl;
                         }
                         return file_put_contents($file, serialize($data));
                     } else {
                         if (!isset(self::$_zendCache)) {
                             self::getZendCache();
                         }
                         return self::$_zendCache->save($data, self::_processId($cacheId), array(), $ttl);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 22
0
 /**
  * Add an item to the cache only if it doesn't already exist
  *
  * @param   string  $key
  * @param   mixed   $value
  * @param   int     $minutes
  * @return  void
  */
 public function add($key, $value, $minutes)
 {
     $key = $this->id($key);
     $seconds = $minutes * 60;
     return $this->apcu ? apcu_add($key, $value, $seconds) : apc_add($key, $value, $seconds);
 }
Ejemplo n.º 23
0
 /**
  * Set a value in the cache if it's not already stored
  *
  * @param string $key
  * @param mixed $value
  * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
  * @return bool
  */
 public function add($key, $value, $ttl = 0)
 {
     return apcu_add($this->getPrefix() . $key, $value, $ttl);
 }
Ejemplo n.º 24
0
 /**
  * Write data for key into cache if it doesn't exist already.
  * If it already exists, it fails and returns false.
  *
  * @param string $key Identifier for the data.
  * @param mixed $value Data to be cached.
  * @return bool True if the data was successfully cached, false on failure.
  * @link http://php.net/manual/en/function.apc-add.php
  */
 public function add($key, $value)
 {
     $key = $this->_key($key);
     $expires = 0;
     $duration = $this->_config['duration'];
     if ($duration) {
         $expires = time() + $duration;
     }
     apcu_add($key . '_expires', $expires, $duration);
     return apcu_add($key, $value, $duration);
 }
Ejemplo n.º 25
0
 /**
  * Stores a value identified by a key into cache if the cache does not contain this key.
  * This is the implementation of the method declared in the parent class.
  *
  * @param string $key the key identifying the value to be cached
  * @param string $value the value to be cached
  * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  * @return boolean true if the value is successfully stored into cache, false otherwise
  */
 protected function addValue($key, $value, $expire)
 {
     return $this->useApcu ? apcu_add($key, $value, $expire) : apc_add($key, $value, $expire);
 }
Ejemplo n.º 26
0
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
$value = 'STRINGTOBECACHED';
if (true === apc_store('artificialkey', $value)) {
    echo 'success storing in apc bc' . PHP_EOL;
}
if ($value === apc_fetch('artificialkey')) {
    echo 'success fetching from apc bc' . PHP_EOL;
}
if (true === apc_delete('artificialkey')) {
    echo 'success deleting from apc bc' . PHP_EOL;
}
if (true === apcu_add('artificialkey', $value)) {
    echo 'success storing in apcu' . PHP_EOL;
}
if ($value === apcu_fetch('artificialkey')) {
    echo 'success fetching from apcu' . PHP_EOL;
}
if (true === apcu_delete('artificialkey')) {
    echo 'success deleting from apcu' . PHP_EOL;
}
Ejemplo n.º 27
0
 public function add($key, $value, $expiration = 0)
 {
     return apcu_add($key, $value, $expiration);
 }
Ejemplo n.º 28
0
 public function routing($request)
 {
     $group = null;
     $route = null;
     $path = trim($request->path, '/');
     $cacheKey = "route_cached_" . $request->host . '_' . base64_encode($path);
     if ($route = \apcu_fetch($cacheKey)) {
         return $route;
     }
     if ($path == null) {
         $path = "/";
     }
     if (!($group = $this->getGroupByDomain($request->host))) {
         if ($path == null && $this->_default_group) {
             $group = $this->_default_group;
         } else {
             $tmp = explode('/', $path);
             $directory = $tmp[0];
             if ($group = $this->getGroupByDirectory($directory)) {
                 unset($tmp[0]);
                 $path = implode('/', $tmp);
             } elseif ($this->_default_group) {
                 //                    $group = $this->_default_group;
             }
             unset($tmp);
         }
     }
     //打补丁 如果没有匹配, 取所有路由循环
     if ($this->_groups && !$group) {
         foreach ($this->_groups as $v) {
             $route = $v->match($path);
             if ($route) {
                 $group = $v;
                 break;
             }
         }
     }
     $group = $group ? $group : $this->_default_group;
     $route = $route ? $route : ($group ? $group->match($path) : null);
     if ($group && $route) {
     } else {
         $route = $this->getRouteByPath($path);
         $route->setPrefix($group->getPrefix());
         //传递所有前缀
         $allPrefix = [];
         if ($this->_groups) {
             foreach ($this->_groups as $k => $v) {
                 $allPrefix[] = $k;
             }
         }
         $route->setAllPrefix($allPrefix);
     }
     if ($route !== null) {
         \apcu_add($cacheKey, $route, 3600);
         return $route;
     }
     return false;
 }
Ejemplo n.º 29
0
 /**
  * Lock cached item
  *
  * @param   string   $id        The cache data ID
  * @param   string   $group     The cache data group
  * @param   integer  $locktime  Cached item max lock time
  *
  * @return  mixed  Boolean false if locking failed or an object containing properties lock and locklooped
  *
  * @since   3.5
  */
 public function lock($id, $group, $locktime)
 {
     $returning = new stdClass();
     $returning->locklooped = false;
     $looptime = $locktime * 10;
     $cache_id = $this->_getCacheId($id, $group) . '_lock';
     $data_lock = apcu_add($cache_id, 1, $locktime);
     if ($data_lock === false) {
         $lock_counter = 0;
         // Loop until you find that the lock has been released.
         // That implies that data get from other thread has finished
         while ($data_lock === false) {
             if ($lock_counter > $looptime) {
                 $returning->locked = false;
                 $returning->locklooped = true;
                 break;
             }
             usleep(100);
             $data_lock = apcu_add($cache_id, 1, $locktime);
             $lock_counter++;
         }
     }
     $returning->locked = $data_lock;
     return $returning;
 }
Ejemplo n.º 30
0
 public function add($key, $value, $timeOut = 0)
 {
     return \apcu_add($key, $value, $timeOut);
 }