/** * increment * * @param mixed $identifier identifier to increment the value for * * @return boolean/int */ public function increment($identifier = null) { if (!$identifier) { throw new \InvalidArgumentException('identifier is a required argument'); } return $this->memcached->increment($this->fileName($identifier)); }
function inc($key) { $key = str_replace('\\', '/', $key); if (!$this->memcached->increment($key)) { $message = sprintf('Memcache::increment() with key "%s" failed', $key); \ManiaLib\Utils\Logger::error($message); } }
public function increment($key, $value) { $this->ensureTriedToConnect(); try { return $this->instance->increment($key, $value); } catch (BaseException $e) { return null; } }
public function collect() { $newValue = $this->memcached->increment($this->key); if (false !== $newValue) { return $this; } if (\Memcached::RES_NOTFOUND !== $this->memcached->getResultCode()) { throw new \Exception('Error collecting value'); } $this->memcached->set($this->key, 1, time() + $this->timeInterval); }
/** * Increment an item. * * Options: * - namespace <string> optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items <boolean> optional * - Throw exception on missing item or return false * * @param string $key * @param int $value * @param array $options * @return int|boolean The new value or false on failure * @throws Exception * * @triggers incrementItem.pre(PreEvent) * @triggers incrementItem.post(PostEvent) * @triggers incrementItem.exception(ExceptionEvent) */ public function incrementItem($key, $value, array $options = array()) { $baseOptions = $this->getOptions(); if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array('key' => &$key, 'options' => &$options)); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); if ($eventRs->stopped()) { return $eventRs->last(); } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $value = (int) $value; $newValue = $this->memcached->increment($internalKey, $value); if ($newValue === false) { if ($this->memcached->get($internalKey) !== false) { throw new Exception\RuntimeException("Memcached::increment('{$internalKey}', {$value}) failed"); } elseif (!$options['ignore_missing_items']) { throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } $this->addItem($key, $value, $options); $newValue = $value; } return $this->triggerPost(__FUNCTION__, $args, $newValue); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } }
/** * {@inheritdoc} */ public function doIncrement($key, $increment = 1, $initialValue = 0, $expiration = null, array $options = array()) { $key = $this->getKey($key, $options); /* Only the binary protocol supports initial value, in which case the implementation is simpler. */ if ($this->isBinaryProtocolActive()) { $result = $this->client->increment($key, $increment, $initialValue, $expiration); return new CacheResponse($result, $this->isSuccess(), $this->isSuccess() || $this->isNotFound()); } /* If the binary protocol is disable we must implement the initial value logic. */ $result = $this->client->increment($key, $increment); /* In case or success or any error aside "not found" there's nothing more to do. */ if ($this->isSuccess() || !$this->isNotFound()) { return new CacheResponse($result, true, true); } /** * Try to add the key; notice that "add" is used instead of "set", to ensure we do not override * the value in case another process already set it. */ $result = $this->client->add($key, $increment + $initialValue, $expiration); /* Created the key successfully. */ if ($this->isSuccess()) { return new CacheResponse($increment + $initialValue, true, true); } /* The key was not stored because is already existed, try to increment a last time. */ if ($this->isNotStored()) { $result = $this->client->increment($key, $increment); return new CacheResponse($result, $this->isSuccess(), $this->isSuccess() || $this->isNotFound()); } return new CacheResponse($result, false, false); }
/** * Internal method to increment an item. * * Options: * - ttl <float> * - The time-to-life * - namespace <string> * - The namespace to use * * @param string $normalizedKey * @param int $value * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); $value = (int)$value; $newValue = $this->memcached->increment($normalizedKey, $value); if ($newValue === false) { $rsCode = $this->memcached->getResultCode(); // initial value if ($rsCode == MemcachedResource::RES_NOTFOUND) { $newValue = $value; $expiration = $this->expirationTime($normalizedOptions['ttl']); $this->memcached->add($normalizedKey, $newValue, $expiration); $rsCode = $this->memcached->getResultCode(); } if ($rsCode) { throw $this->getExceptionByResultCode($rsCode); } } return $newValue; }
/** * Increment a numeric item's value. * * @link http://www.php.net/manual/en/memcached.increment.php * * @param string $key The key under which to store the value. * @param int $offset The amount by which to increment the item's value. * @param string $group The group value appended to the $key. * @return int|bool Returns item's new value on success or FALSE on failure. */ public function increment($key, $offset = 1, $group = 'default') { $derived_key = $this->buildKey($key, $group); // Increment values in no_mc_groups if (in_array($group, $this->no_mc_groups)) { // Only increment if the key already exists and the number is currently 0 or greater (mimics memcached behavior) if (isset($this->cache[$derived_key]) && $this->cache[$derived_key] >= 0) { // If numeric, add; otherwise, consider it 0 and do nothing if (is_numeric($this->cache[$derived_key])) { $this->cache[$derived_key] += (int) $offset; } else { $this->cache[$derived_key] = 0; } // Returned value cannot be less than 0 if ($this->cache[$derived_key] < 0) { $this->cache[$derived_key] = 0; } return $this->cache[$derived_key]; } else { return false; } } $result = $this->mc->increment($derived_key, $offset); if (Memcached::RES_SUCCESS === $this->getResultCode()) { $this->add_to_internal_cache($derived_key, $result); } return $result; }
/** * Increment an item. * * Options: * - namespace <string> optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items <boolean> optional * - Throw exception on missing item or return false * * @param string $key * @param int $value * @param array $options * @return int|boolean The new value or false on failure * @throws Exception * * @triggers incrementItem.pre(PreEvent) * @triggers incrementItem.post(PostEvent) * @triggers incrementItem.exception(ExceptionEvent) */ public function incrementItem($key, $value, array $options = array()) { $baseOptions = $this->getOptions(); if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array('key' => &$key, 'value' => &$value, 'options' => &$options)); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); if ($eventRs->stopped()) { return $eventRs->last(); } $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); $value = (int) $value; $newValue = $this->memcached->increment($key, $value); if ($newValue === false) { if (($rsCode = $this->memcached->getResultCode()) != 0 && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items'])) { throw $this->getExceptionByResultCode($rsCode); } $expiration = $this->expirationTime($options['ttl']); if (!$this->memcached->add($key, $value, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } $newValue = $value; } return $this->triggerPost(__FUNCTION__, $args, $newValue); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } }
/** * Increase a stored number * * @param string $key * @param int $step * @return int | bool */ public function inc($key, $step = 1) { $this->add($key, 0); $result = self::$cache->increment($this->getPrefix() . $key, $step); $this->verifyReturnCode(); return $result; }
/** * Flood protection with Memcached * * @param string $misprintHash * @throws Exception if report is flood-positive * @return boolean */ protected function floodProtect($misprintHash) { if (!$this->memcached) { return false; } $ip = $this->getIP(); if ($ip !== false) { $mcIpHash = 'newrphus:byIP:' . md5($ip); $attemptsCount = $this->memcached->get($mcIpHash); if ($this->memcached->getResultCode() === 0) { if ($attemptsCount > $this->attemptsThreshold) { throw new Exception("Too many attempts", 429); } $this->memcached->increment($mcIpHash); } else { $this->memcached->set($mcIpHash, 1, 300); } } $mcTextHash = 'newrphus:byText:' . $misprintHash; $this->memcached->get($mcTextHash); if ($this->memcached->getResultCode() === 0) { throw new Exception("This misprint already was sent", 202); } $this->memcached->set($mcTextHash, true, 300); return true; }
/** * {@inheritdoc} */ public function inc($name, $delta = 1) { if (!$this->has($name)) { $this->forever($name, $delta); return $delta; } return $this->driver->increment($name, $delta); }
/** * Increase a stored number * * @param string $key * @param int $step * @return int | bool */ public function inc($key, $step = 1) { $this->add($key, 0); $result = self::$cache->increment($this->getPrefix() . $key, $step); if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) { return false; } return $result; }
/** * @inheritdoc */ public function increment($key, $offset = 1, $expire = 0, $create = true) { $hash = $this->prepareKey($key); if ($this->exists($key) === false) { if ($create === false) { return false; } $this->storage->add($hash, 0, $expire); } return $this->storage->increment($hash, $offset); }
/** * (non-PHPdoc) * @see \Cachearium\Backend\CacheRAM::cleanP() */ public function cleanP($base, $id) { // @codeCoverageIgnoreStart if (!$this->enabled) { throw new NotCachedException(); } // @codeCoverageIgnoreEnd $group = $this->getGroupString(new CacheKey($base, $id)); parent::cleanP($base, $id); $this->memcached->increment($group); return true; }
function handle($pKey, $userKey) { $this->privateKey = $pKey; $this->userKey = $userKey; $memcache = new Memcached(); if ($this->rateUsed = $memcache->get($this->memcacheKey())) { $memcache->increment($this->memcacheKey(), 1); $this->rateUsed += 1; } else { $memcache->add($this->memcacheKey(), 1, $this->getNextResetTime()); $this->rateUsed = 1; } return $this->isValid(); }
/** * 递减 * @param string $key 键名 * @param int $step 递减步长 * @return int|false 递减后的值,失败返回false */ public function decr($key, $step = 1) { if (!is_int($step)) { return false; } try { $value = $this->handler->get($key); if ($value === false && $this->handler->getResultCode() === \Memcached::RES_NOTFOUND) { if ($this->handler->set($key, $value = -$step)) { return $value; } } else { //memcache会将数字存储为字符串 if (!is_numeric($value)) { return false; } $timeValue = self::getValue($this->handler->get(self::timeKey($key))); //未设置过期时间或未过期 if ($timeValue === false && $this->handler->getResultCode() === \Memcached::RES_NOTFOUND || isset($timeValue['expire_time']) && $timeValue['expire_time'] > time()) { //memcache 新的元素的值不会小于0 if ($value < 0 || $step > 0 && $value < $step) { if ($this->handler->set($key, $value -= $step)) { return $value; } } else { if ($step > 0) { $ret = $this->handler->decrement($key, $step); return $ret; } else { return $this->handler->increment($key, -$step); } } } //已过期,重新设置 if ($this->handler->set($key, $value = $step)) { return $value; } } return false; } catch (Exception $ex) { self::exception($ex); //连接状态置为false $this->isConnected = false; } return false; }
/** * Internal method to increment an item. * * @param string $normalizedKey * @param int $value * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalIncrementItem(&$normalizedKey, &$value) { $value = (int) $value; $newValue = $this->memcached->increment($normalizedKey, $value); if ($newValue === false) { $rsCode = $this->memcached->getResultCode(); // initial value if ($rsCode == MemcachedResource::RES_NOTFOUND) { $newValue = $value; $this->memcached->add($normalizedKey, $newValue, $this->expirationTime()); $rsCode = $this->memcached->getResultCode(); } if ($rsCode) { throw $this->getExceptionByResultCode($rsCode); } } return $newValue; }
/** * {@inheritdoc} */ public function increment($key, $amount = 1, $options = array()) { if (!$this->online()) { return Gdn_Cache::CACHEOP_FAILURE; } $finalOptions = array_merge($this->StoreDefaults, $options); $initial = val(Gdn_Cache::FEATURE_INITIAL, $finalOptions, 0); $expiry = val(Gdn_Cache::FEATURE_EXPIRY, $finalOptions, 0); $requireBinary = $initial || $expiry; $initial = !is_null($initial) ? $initial : 0; $expiry = !is_null($expiry) ? $expiry : 0; $tryBinary = $this->option(Memcached::OPT_BINARY_PROTOCOL, false) & $requireBinary; $realKey = $this->makeKey($key, $finalOptions); switch ($tryBinary) { case false: $incremented = $this->memcache->increment($realKey, $amount); if (is_null($incremented) && $initial) { $incremented = $this->memcache->set($realKey, $initial); if ($incremented) { $incremented = $initial; } } break; case true: $incremented = $this->memcache->increment($realKey, $amount, $initial, $expiry); break; } // Check if things went ok $ok = $this->lastAction($realKey); if (!$ok) { return Gdn_Cache::CACHEOP_FAILURE; } if ($incremented !== false) { Gdn_Cache::localSet($realKey, $incremented); return $incremented; } return Gdn_Cache::CACHEOP_FAILURE; }
public function testPassingNullKey() { $memcached = new Memcached(); $this->assertFalse($memcached->add(null, 1)); $this->assertFalse($memcached->replace(null, 1)); $this->assertFalse($memcached->set(null, 1)); $this->assertFalse($memcached->increment(null)); $this->assertFalse($memcached->decrement(null)); }
/** * @inheritdoc */ public function increment($name, $offset = 1) { return $this->driver->increment($name, $offset); }
/** * {@inheritdoc} */ public function increment($key, $amount = 1) { return $this->memcached->increment($this->getKey($key), $amount); }
/** * Increments the group value to simulate deletion of all keys under a group * old values will remain in storage until they expire. * * @param string $group name of the group to be cleared * @return bool success */ public function clearGroup($group) { return (bool) $this->_Memcached->increment($this->_config['prefix'] . $group); }
/** * Increment the value of an item in the cache. * * @param string $key * @param mixed $value * @return int|bool */ public function increment($key, $value = 1) { return $this->memcached->increment($this->prefix . $key, $value); }
public function inc($key) { $this->cas($key, 0); return $this->memcached->increment($key); }
/** * 增加整数数据的值 * * @param string $key * @param int $offset * @return bool */ public function increment($key, $offset = 1) { return $this->memcached ? $this->memcached->increment($key, $offset) : false; }
/** * Получение текущего evid или инкремент текущего evid и получения нового. * Здесь необходимо подключаться к memcached напрямую без memBuff и всех его "обвесов", чтобы * делать инкремент штатными средствами. Если делать это с помощью set/get может возникнуть * ситуация когда два процесса получат одинковый evid, сделают инкремент и оба перезапишут * одинаковое значение, из-за этого все сломается :). * * evid это счетчик событий. Когда создается новое событие, счетчик инкрементируется. * Каждое подключение знает какое последние событие оно выполнило и по evid ориентируется есть ли * новые. * * @param bool $inc если true -> инкрементирует evid и возвращает новое значение, иначе текущее * * @return int новое или текущее значение evid */ private function _counter($name, $inc = 0) { if (empty($this->_memcache) || $inc) { $this->_memcache = new Memcached(); $svk = $GLOBALS[memBuff::SERVERS_VARKEY]; if (empty($GLOBALS[$svk])) { $svk = 'memcachedServers'; } if (!($servers = $GLOBALS[$svk])) { self::error(1, true); } foreach ($servers as $s) { $bIsConnected = $this->_memcache->addServer($s, 11211); } if (!$bIsConnected) { self::error(1, true); } } $key = self::MEMBUFF_COUNTERS_KEY . $this->_uid . ':' . $name . (defined('SERVER') ? SERVER : ''); if ($inc) { $v = $inc > 0 ? $this->_memcache->increment($key, $inc) : $this->_memcache->decrement($key, $inc * -1); } else { $v = $this->_memcache->get($key); } if ($v === false) { $start = $name == 'connects' ? 1 : 0; $this->_memcache->set($key, $start, $name == 'evid' ? 0 : self::CONNECT_TTL * 1.3); } return (int) $v; }
/** * Increase a stored number * * @param string $key * @param int $step * @return int | bool */ public function inc($key, $step = 1) { $this->add($key, 0); return self::$cache->increment($this->getPrefix() . $key, $step); }
/** * Clear by namespace * @param string $namespace * @return boolean success or failure */ public function clearByNamespace($namespace) { $version_key = $this->getVersionKey($namespace); return $this->connect->increment($version_key); }
<?php const key = 'incr_decr_test'; $mc = new Memcached(); $mc->addServer('127.0.0.1', 11211); $mc->set(key, 0); var_dump($mc->get(key)); $mc->increment(key, 3); var_dump($mc->get(key)); $mc->decrement(key, 1); var_dump($mc->get(key)); //increment with initial value only works with binary protocol const non_existant_key = 'incr_decr_test_fail'; $mc2 = new Memcached(); $mc2->setOption(Memcached::OPT_BINARY_PROTOCOL, true); $mc2->addServer('127.0.0.1', 11211); var_dump($mc2->increment(non_existant_key, 3)); var_dump($mc2->getMulti(array(non_existant_key))); var_dump($mc2->decrement(non_existant_key, 1)); var_dump($mc2->getMulti(array(non_existant_key))); // There is an issue with the return value from this section, especially as it // changes when memcached isn't clean - even with the delete below. $mc2->increment(non_existant_key, 3, 1); $result = $mc2->getMulti(array(non_existant_key)); var_dump($result[non_existant_key]); // Cleanup $mc2->delete(non_existant_key);