Ejemplo n.º 1
0
 /**
  * Decrement 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 or failure
  * @throws Exception
  *
  * @triggers decrementItem.pre(PreEvent)
  * @triggers decrementItem.post(PostEvent)
  * @triggers decrementItem.exception(ExceptionEvent)
  */
 public function decrementItem($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->decrement($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);
     }
 }
Ejemplo n.º 2
0
    /**
     * Internal method to decrement 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 internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions)
    {
        $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']);

        $value    = (int)$value;
        $newValue = $this->memcached->decrement($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;
    }
 /**
  * Decrement a numeric item's value.
  *
  * @link http://www.php.net/manual/en/memcached.decrement.php
  *
  * @param string    $key    The key under which to store the value.
  * @param int       $offset The amount by which to decrement 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 decrement($key, $offset = 1, $group = 'default')
 {
     $derived_key = $this->buildKey($key, $group);
     // Decrement values in no_mc_groups
     if (in_array($group, $this->no_mc_groups)) {
         // Only decrement if the key already exists and value is 0 or greater (mimics memcached behavior)
         if (isset($this->cache[$derived_key]) && $this->cache[$derived_key] >= 0) {
             // If numeric, subtract; 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->decrement($derived_key, $offset);
     if (Memcached::RES_SUCCESS === $this->getResultCode()) {
         $this->add_to_internal_cache($derived_key, $result);
     }
     return $result;
 }
Ejemplo n.º 4
0
 /**
  * Decrement 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 or failure
  * @throws Exception
  *
  * @triggers decrementItem.pre(PreEvent)
  * @triggers decrementItem.post(PostEvent)
  * @triggers decrementItem.exception(ExceptionEvent)
  */
 public function decrementItem($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->decrement($internalKey, $value);
         if ($newValue === false) {
             if ($this->memcached->get($internalKey) !== false) {
                 throw new Exception\RuntimeException("Memcached::decrement('{$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);
     }
 }
Ejemplo n.º 5
0
 /**
  * Decrease a stored number
  *
  * @param string $key
  * @param int $step
  * @return int | bool
  */
 public function dec($key, $step = 1)
 {
     $result = self::$cache->decrement($this->getPrefix() . $key, $step);
     if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
         return false;
     }
     return $result;
 }
Ejemplo n.º 6
0
 public function decrement($key, $value)
 {
     $this->ensureTriedToConnect();
     try {
         return $this->instance->decrement($key, $value);
     } catch (BaseException $e) {
         return null;
     }
 }
Ejemplo n.º 7
0
 /**
  * @inheritdoc
  */
 public function decrement($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, 1, $expire);
     }
     return $this->storage->decrement($hash, $offset);
 }
Ejemplo n.º 8
0
 /**
  * 递减
  * @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;
 }
Ejemplo n.º 9
0
 /**
  * Internal method to decrement an item.
  *
  * @param  string $normalizedKey
  * @param  int    $value
  * @return int|boolean The new value on success, false on failure
  * @throws Exception\ExceptionInterface
  */
 protected function internalDecrementItem(&$normalizedKey, &$value)
 {
     $value = (int) $value;
     $newValue = $this->memcached->decrement($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;
 }
Ejemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function decrement($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, null);
     $expiry = val(Gdn_Cache::FEATURE_EXPIRY, $finalOptions, null);
     $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:
             $decremented = $this->memcache->decrement($realKey, $amount);
             if (is_null($decremented) && $initial) {
                 $decremented = $this->memcache->set($realKey, $initial);
                 if ($decremented) {
                     $decremented = $initial;
                 }
             }
             break;
         case true:
             $decremented = $this->memcache->decrement($realKey, $amount, $initial, $expiry);
             break;
     }
     // Check if things went ok
     $ok = $this->lastAction($realKey);
     if (!$ok) {
         return Gdn_Cache::CACHEOP_FAILURE;
     }
     if ($decremented !== false) {
         Gdn_Cache::localSet($realKey, $decremented);
         return $decremented;
     }
     return Gdn_Cache::CACHEOP_FAILURE;
 }
Ejemplo n.º 11
0
 /**
  * 减少整数数据的值
  *
  * @param string $key
  * @param int $offset
  * @return bool
  */
 public function decrement($key, $offset = 1)
 {
     return $this->memcached ? $this->memcached->decrement($key, $offset) : false;
 }
Ejemplo n.º 12
0
 /**
  * Получение текущего 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;
 }
Ejemplo n.º 13
0
 /**
  * Decrease a stored number
  *
  * @param string $key
  * @param int $step
  * @return int | bool
  */
 public function dec($key, $step = 1)
 {
     return self::$cache->decrement($this->getPrefix() . $key, $step);
 }
Ejemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function decrement($name, $delta = 1)
 {
     return $this->service->decrement($name, $delta);
 }
Ejemplo n.º 15
0
 public function decrement($key, $by_value)
 {
     return $this->memcached->decrement($key, $by_value);
 }
Ejemplo n.º 16
0
 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));
 }
Ejemplo n.º 17
0
 /**
  * {@inheritdoc}
  */
 public function decrement($key, $amount = 1)
 {
     return $this->memcached->decrement($this->getKey($key), $amount);
 }
Ejemplo n.º 18
0
 /**
  * {@inheritdoc}
  */
 public function dec($name, $delta = 1)
 {
     return $this->driver->decrement($name, $delta);
 }
Ejemplo n.º 19
0
<?php

$mc = new Memcached();
$mc->addServer('127.0.0.1', 11211);
$mc->addServer('127.0.0.1', 11212);
for ($i = 1; $i <= 10; $i++) {
    $key = "dec_test_{$i}";
    $mc->set($key, 10);
    var_dump($mc->get($key) === 10);
    $mc->decrement($key, 1);
    var_dump($mc->get($key) === 9);
}
Ejemplo n.º 20
0
 /**
  * Decrement a cache key with $step
  *
  * @param string  $key   Cache key
  * @param int     $step  Increment step
  *
  * @return int Value after decrement
  */
 public function dec($key, $step = 1)
 {
     return $this->memcached->decrement($this->nsKey($key), $step);
 }
Ejemplo n.º 21
0
 /**
  * Decreases the value
  *
  * @param   string  $key
  * @param   int     $value
  * @return  void
  */
 public function decrement($key, $value = 1)
 {
     $this->_memcached->decrement($this->_prefix . $key, $value);
 }
Ejemplo n.º 22
0
<?php

$cache = new Memcached();
$cache->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$cache->setOption(Memcached::OPT_COMPRESSION, false);
$cache->addServer('localhost', 3434);
$cache->add("add_key", "hello", 500);
$cache->append("append_key", "world");
$cache->prepend("prepend_key", "world");
$cache->increment("incr", 2, 1, 500);
$cache->decrement("decr", 2, 1, 500);
$cache->delete("delete_k");
$cache->flush(1);
var_dump($cache->get('get_this'));
$cache->set('set_key', 'value 1', 100);
$cache->replace('replace_key', 'value 2', 200);
$cache->getStats();
$cache->quit();
sleep(1);
Ejemplo n.º 23
0
<?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));
Ejemplo n.º 24
0
 /**
  * Decrement the value of an item in the cache.
  *
  * @param  string  $key
  * @param  mixed   $value
  * @return int|bool
  */
 public function decrement($key, $value = 1)
 {
     return $this->memcached->decrement($this->prefix . $key, $value);
 }
Ejemplo n.º 25
0
 /**
  * Decrements the value of an integer cached key
  *
  * @param string $key Identifier for the data
  * @param int $offset How much to subtract
  * @return bool|int New decremented value, false otherwise
  */
 public function decrement($key, $offset = 1)
 {
     $key = $this->_key($key);
     return $this->_Memcached->decrement($key, $offset);
 }
Ejemplo n.º 26
0
<?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);
Ejemplo n.º 27
0
 /**
  * @inheritdoc
  */
 public function decrement($name, $offset = 1)
 {
     return $this->driver->decrement($name, $offset);
 }
Ejemplo n.º 28
0
 /**
  * Decrease a stored number
  *
  * @param string $key
  * @param int $step
  * @return int | bool
  */
 public function dec($key, $step = 1)
 {
     $result = self::$cache->decrement($this->getPrefix() . $key, $step);
     $this->verifyReturnCode();
     return $result;
 }
Ejemplo n.º 29
0
 /**
  * {@inheritdoc}
  */
 protected function decrementValue($key, $value)
 {
     return $this->driver->decrement($key, $value);
 }
Ejemplo n.º 30
0
 public function decrement($key, $value = 1)
 {
     return parent::decrement($this->key($key), $value);
 }