Ejemplo n.º 1
0
 /**
  * 新增key
  * @param $key
  * @param $val
  * @param $expireTime
  * @return bool
  */
 public function add($key, $val, $expireTime)
 {
     $ret = $this->dbh->add($key, $val, $expireTime);
     if ($ret === false) {
         $this->error('add', $key);
     }
     return true;
 }
Ejemplo n.º 2
0
 function add($key, $value, $ttl = 0)
 {
     $key = str_replace('\\', '/', $key);
     if (!$this->memcached->add($key, $value, $ttl)) {
         $message = sprintf('Memcache::set() with key "%s" failed', $key);
         \ManiaLib\Utils\Logger::error($message);
     }
 }
Ejemplo n.º 3
0
 public function add($id, $value, $ttl = null)
 {
     $ttl = $ttl ?: 0;
     if ($ttl > 0) {
         $ttl = time() + $ttl;
     }
     return $this->memcached->add($id, $value, $ttl);
 }
Ejemplo n.º 4
0
 public function exists($id)
 {
     $success = $this->memcached->add($id, 0);
     if (!$success) {
         return true;
     }
     $this->memcached->delete($id);
     return false;
 }
Ejemplo n.º 5
0
 /**
  * Lock the mutex
  *
  * @param string $mutexKey Identifier of the mutex.
  * @param int    $expiry   How long in seconds to keep the mutex locked just in
  *                         case the script dies. 0 = never expires.
  *
  * @throws LockFailedException
  */
 public function lock($mutexKey, $expiry)
 {
     // Try and set the value. If it fails check to see if
     // it already contains our ID
     if (!$this->_memcache->add($mutexKey, $this->_getLockId(), $expiry)) {
         if (!$this->isLocked($mutexKey)) {
             throw new LockFailedException();
         }
     }
 }
Ejemplo n.º 6
0
 /**
  * 上锁
  *
  * @param string $key
  * @return boolean
  */
 public function acquire($key)
 {
     $key = $this->prefix . $key;
     $time = time();
     while (time() - $time < $this->max_timeout) {
         if ($this->memcached->add($key, $this->Identifier, $this->timeout)) {
             return true;
         }
         usleep($this->retry_wait_usec);
     }
     return false;
 }
Ejemplo n.º 7
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;
    }
 /**
  * {@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);
 }
Ejemplo n.º 9
0
 /**
  * 批量设置键值(当键名不存在时);<br>
  * 只有当键值全部设置成功时,才返回true,否则返回false并尝试回滚
  * @param array $sets   键值数组
  * @return boolean      是否成功
  */
 public function mSetNX($sets)
 {
     try {
         $keys = [];
         $status = true;
         foreach ($sets as $key => $value) {
             $status = $this->handler->add($key, self::setValue($value));
             if ($status) {
                 $keys[] = $key;
             } else {
                 break;
             }
         }
         //如果失败,尝试回滚,但不保证成功
         if (!$status) {
             foreach ($keys as $key) {
                 $this->handler->delete($key);
             }
         }
         return $status;
     } catch (Exception $ex) {
         self::exception($ex);
         //连接状态置为false
         $this->isConnected = false;
     }
     return false;
 }
Ejemplo n.º 10
0
	/**
	 * Lock cache index
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   12.1
	 */
	protected function lockindex()
	{
		$looptime = 300;
		$data_lock = self::$_db->add($this->_hash . '-index_lock', 1, 30);

		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)
				{
					return false;
					break;
				}

				usleep(100);
				$data_lock = self::$_db->add($this->_hash . '-index_lock', 1, 30);
				$lock_counter++;
			}
		}

		return true;
	}
Ejemplo n.º 11
0
 /**
  * Add an item.
  *
  * Options:
  *  - namespace <string> optional
  *    - The namespace to use (Default: namespace of object)
  *  - tags <array> optional
  *    - An array of tags
  *
  * @param  string $key
  * @param  mixed  $value
  * @param  array  $options
  * @return boolean
  * @throws Exception
  *
  * @triggers addItem.pre(PreEvent)
  * @triggers addItem.post(PostEvent)
  * @triggers addItem.exception(ExceptionEvent)
  */
 public function addItem($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();
         }
         $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key;
         if (!$this->memcached->add($internalKey, $value, $options['ttl'])) {
             if ($this->memcached->get($internalKey) !== false) {
                 throw new Exception\RuntimeException("Key '{$internalKey}' already exists");
             }
             $type = is_object($value) ? get_class($value) : gettype($value);
             throw new Exception\RuntimeException("Memcached::add('{$internalKey}', <{$type}>, {$options['ttl']}) failed");
         }
         $result = true;
         return $this->triggerPost(__FUNCTION__, $args, $result);
     } catch (\Exception $e) {
         return $this->triggerException(__FUNCTION__, $args, $e);
     }
 }
Ejemplo n.º 12
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.º 13
0
 /**
  * 添加数据
  * @param string|array $key
  * @param mixed $value
  * @param int $expiration
  * @return array|bool
  */
 public function add($key = NULL, $value = NULL, $expiration = 0)
 {
     if (is_null($expiration)) {
         $expiration = C(Config::MEMCACHE_EXPIRATION);
     }
     $expiration = intval($expiration);
     if (is_array($key)) {
         foreach ($key as $multi) {
             if (!isset($multi['expiration']) || $multi['expiration'] == '') {
                 $multi['expiration'] = $expiration;
             }
             $this->add($this->key_name($multi['key']), $multi['value'], $multi['expiration']);
         }
         $add_status = true;
     } else {
         $keyName = $this->key_name($key);
         $this->local_cache[$keyName] = $value;
         switch ($this->client_type) {
             case 'Memcache':
                 $add_status = $this->m->add($keyName, $value, C(Config::MEMCACHE_COMPRESSION), $expiration);
                 break;
             default:
             case 'Memcached':
                 $add_status = $this->m->add($keyName, $value, $expiration);
                 break;
         }
     }
     return $add_status;
 }
Ejemplo n.º 14
0
 /**
  * Adds a value to cache.
  *
  * If the specified key already exists, the value is not stored and the function
  * returns false.
  *
  * @link    http://www.php.net/manual/en/memcached.add.php
  *
  * @param   string      $key            The key under which to store the value.
  * @param   mixed       $value          The value to store.
  * @param   string      $group          The group value appended to the $key.
  * @param   int         $expiration     The expiration time, defaults to 0.
  * @param   string      $server_key     The key identifying the server to store the value on.
  * @param   bool        $byKey          True to store in internal cache by key; false to not store by key
  * @return  bool                        Returns TRUE on success or FALSE on failure.
  */
 public function add($key, $value, $group = 'default', $expiration = 0, $server_key = '', $byKey = false)
 {
     /**
      * Ensuring that wp_suspend_cache_addition is defined before calling, because sometimes an advanced-cache.php
      * file will load object-cache.php before wp-includes/functions.php is loaded. In those cases, if wp_cache_add
      * is called in advanced-cache.php before any more of WordPress is loaded, we get a fatal error because
      * wp_suspend_cache_addition will not be defined until wp-includes/functions.php is loaded.
      */
     if (function_exists('wp_suspend_cache_addition') && wp_suspend_cache_addition()) {
         return false;
     }
     $derived_key = $this->buildKey($key, $group);
     $expiration = $this->sanitize_expiration($expiration);
     // If group is a non-Memcached group, save to runtime cache, not Memcached
     if (in_array($group, $this->no_mc_groups)) {
         // Add does not set the value if the key exists; mimic that here
         if (isset($this->cache[$derived_key])) {
             return false;
         }
         $this->add_to_internal_cache($derived_key, $value);
         return true;
     }
     // Save to Memcached
     if (false !== $byKey) {
         $result = $this->mc->addByKey($server_key, $derived_key, $value, $expiration);
     } else {
         $result = $this->mc->add($derived_key, $value, $expiration);
     }
     // Store in runtime cache if add was successful
     if (Memcached::RES_SUCCESS === $this->getResultCode()) {
         $this->add_to_internal_cache($derived_key, $value);
     }
     return $result;
 }
Ejemplo n.º 15
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
  * @throws \Exception
  */
 public function add($key, $value, $ttl = 0)
 {
     $result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
     if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
         $this->verifyReturnCode();
     }
     return $result;
 }
Ejemplo n.º 16
0
 public function set($key, $value)
 {
     $this->get($key);
     if (!$value) {
         throw new StorageException('[STORAGE] Given value for "' . $this->getStorageName() . '::set" not valid! Key: ' . $key);
     }
     if ($this->memcachedObj->getResultCode() == \Memcached::RES_NOTFOUND) {
         $this->memcachedObj->add($key, $value);
         unset($this->casArray[$key]);
     } else {
         $this->memcachedObj->cas($this->casArray[$key], $key, $value);
     }
     $resultCode = $this->memcachedObj->getResultCode();
     if ($resultCode != \Memcached::RES_SUCCESS) {
         throw new StorageException('[STORAGE] "' . $this->getStorageName() . '::set" failed!' . ' StorageRespCode: ' . $resultCode . ', Key: ' . $key . ', Cas: ' . (isset($this->casArray[$key]) ? $this->casArray[$key] : 'null'));
     }
     return $resultCode;
 }
Ejemplo n.º 17
0
 /**
  * Add a key to the cache if it does not already exist.
  *
  * @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.
  */
 public function add($key, $value)
 {
     $duration = $this->_config['duration'];
     if ($duration > 30 * DAY) {
         $duration = 0;
     }
     $key = $this->_key($key);
     return $this->_Memcached->add($key, $value, $duration);
 }
Ejemplo n.º 18
0
/**
 * 	Save data into a memory area shared by all users, all sessions on server
 *
 *  @param	string      $memoryid		Memory id of shared area
 * 	@param	string		$data			Data to save
 * 	@return	int							<0 if KO, Nb of bytes written if OK
 */
function dol_setcache($memoryid, $data)
{
    global $conf;
    $result = 0;
    // Using a memcached server
    if (!empty($conf->memcached->enabled) && class_exists('Memcached')) {
        global $dolmemcache;
        if (empty($dolmemcache) || !is_object($dolmemcache)) {
            $dolmemcache = new Memcached();
            $tmparray = explode(':', $conf->global->MEMCACHED_SERVER);
            $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211);
            if (!$result) {
                return -1;
            }
        }
        $memoryid = session_name() . '_' . $memoryid;
        //$dolmemcache->setOption(Memcached::OPT_COMPRESSION, false);
        //print "Add memoryid=".$memoryid;
        $dolmemcache->add($memoryid, $data);
        // This fails if key already exists
        $rescode = $dolmemcache->getResultCode();
        if ($rescode == 0) {
            return count($data);
        } else {
            return -$rescode;
        }
    } else {
        if (!empty($conf->memcached->enabled) && class_exists('Memcache')) {
            global $dolmemcache;
            if (empty($dolmemcache) || !is_object($dolmemcache)) {
                $dolmemcache = new Memcache();
                $tmparray = explode(':', $conf->global->MEMCACHED_SERVER);
                $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211);
                if (!$result) {
                    return -1;
                }
            }
            $memoryid = session_name() . '_' . $memoryid;
            //$dolmemcache->setOption(Memcached::OPT_COMPRESSION, false);
            $result = $dolmemcache->add($memoryid, $data);
            // This fails if key already exists
            if ($result) {
                return count($data);
            } else {
                return -1;
            }
        } else {
            if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && $conf->global->MAIN_OPTIMIZE_SPEED & 0x2) {
                $result = dol_setshmop($memoryid, $data);
            }
        }
    }
    return $result;
}
Ejemplo n.º 19
0
 public function cas($key, $value)
 {
     if (($rValue = $this->memcached->get($key, null, $token)) !== false) {
         return $rValue;
     }
     if ($this->memcached->getResultCode() === Memcached::RES_NOTFOUND) {
         $this->memcached->add($key, $value);
     } else {
         $this->memcached->cas($token, $key, $value);
     }
     return $value;
 }
Ejemplo n.º 20
0
 /**
  * (non-PHPdoc)
  *
  * @see Memcached::addServer()
  *
  * @abstract indicator of a positive connection should be returned
  */
 public function addServer($host, $port, $weight = null)
 {
     $this->is_connected = parent::addServer($host, $port, $weight);
     // Get the Cache Listing
     $this->cache_listing = parent::get('cache_listing');
     if ($this->cache_listing === FALSE) {
         parent::add('cache_listing', array());
         $this->cache_listing = array();
     }
     // check sum for the saving process
     $this->_md5_sum = md5(serialize($this->cache_listing));
 }
Ejemplo n.º 21
0
 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();
 }
Ejemplo n.º 22
0
 /**
  * @param $keyword
  * @param string $value
  * @param int $time
  * @param array $option
  * @return bool
  */
 public function driver_set($keyword, $value = '', $time = 300, $option = array())
 {
     $this->connectServer();
     // Memcache will only allow a expiration timer less than 2592000 seconds,
     // otherwise, it will assume you're giving it a UNIX timestamp.
     if ($time > 2592000) {
         $time = time() + $time;
     }
     if (isset($option['isExisting']) && $option['isExisting'] == true) {
         return $this->instant->add($keyword, $value, $time);
     } else {
         return $this->instant->set($keyword, $value, $time);
     }
 }
Ejemplo n.º 23
0
/**
 * 	\brief      Save data into a memory area shared by all users, all sessions on server
 *  \param      $memoryid		Memory id of shared area
 * 	\param		$data			Data to save
 * 	\return		int				<0 if KO, Nb of bytes written if OK
 */
function dol_setcache($memoryid,$data)
{
	global $conf;
	$result=0;

	// Using a memcached server
	if (! empty($conf->memcached->enabled) && class_exists('Memcached'))
	{
		$memoryid=session_name().'_'.$memoryid;
		$m=new Memcached();
		$tmparray=explode(':',$conf->global->MEMCACHED_SERVER);
		$result=$m->addServer($tmparray[0], $tmparray[1]?$tmparray[1]:11211);
		//$m->setOption(Memcached::OPT_COMPRESSION, false);
		$m->add($memoryid,$data);
		$rescode=$m->getResultCode();
		if ($rescode == 0)
		{
			return sizeof($data);
		}
		else
		{
			return -$rescode;
		}
	}
	else if (! empty($conf->memcached->enabled) && class_exists('Memcache'))
	{
		$memoryid=session_name().'_'.$memoryid;
		$m=new Memcache();
		$tmparray=explode(':',$conf->global->MEMCACHED_SERVER);
		$result=$m->addServer($tmparray[0], $tmparray[1]?$tmparray[1]:11211);
		//$m->setOption(Memcached::OPT_COMPRESSION, false);
		$result=$m->add($memoryid,$data);
		if ($result)
		{
			return sizeof($data);
		}
		else
		{
			return -1;
		}
	}
	// Using shmop
	else if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x02))
	{
		$result=dol_setshmop($memoryid,$data);
	}

	return $result;
}
Ejemplo n.º 24
0
 /**
  * Set a value in cache if it doesn't already exist. Internally, this uses
  * Memcache::add
  *
  * @param string $key
  * @param mixed $value
  * @param integer $ttl
  * @return boolean
  */
 public function setIfNotExists($key, $value, $ttl = self::DEFAULT_TTL)
 {
     if (!$this->hasConnection()) {
         // @codeCoverageIgnoreStart
         return false;
         // @codeCoverageIgnoreEnd
     }
     try {
         return $this->memcached->add($this->getKeyString($key), $value, $ttl);
         // @codeCoverageIgnoreStart
     } catch (\Exception $e) {
     }
     return false;
     // @codeCoverageIgnoreEnd
 }
Ejemplo n.º 25
0
 /**
  * Namespace a key.
  *
  * @since 151216 Memcached utilities.
  *
  * @param string     $primary_key Primary key.
  * @param string|int $sub_key     Sub-key.
  *
  * @return string Full namespaced cache key.
  */
 protected function key(string $primary_key, $sub_key) : string
 {
     if (!$this->Pool) {
         return '';
         // Not possible.
     }
     if (!($namespaced_primary_key = $this->nspKey($primary_key))) {
         return '';
         // Not possible; e.g., empty key.
     }
     $namespaced_primary_key_uuid = '';
     // Initialize.
     do {
         // Avoid race issues with a loop.
         $attempts = $attempts ?? 0;
         ++$attempts;
         // Counter.
         if ($existing_namespaced_primary_key_uuid = (string) $this->Pool->get($namespaced_primary_key)) {
             $namespaced_primary_key_uuid = $existing_namespaced_primary_key_uuid;
             break;
             // All good; stop here.
         }
         if (!isset($new_namespaced_primary_key_uuid)) {
             $new_namespaced_primary_key_uuid = $this->c::uuidV4();
         }
         if ($this->Pool->add($namespaced_primary_key, $new_namespaced_primary_key_uuid)) {
             $namespaced_primary_key_uuid = $new_namespaced_primary_key_uuid;
             break;
             // All good; stop here.
         }
         $result_code = $this->Pool->getResultCode();
         //
     } while ($attempts < $this::MAX_WRITE_ATTEMPTS && $result_code === \Memcached::RES_NOTSTORED);
     if (!$namespaced_primary_key_uuid) {
         return '';
         // Failure; e.g., race condition.
     }
     $sub_key = (string) $sub_key;
     $namespaced_primary_key_uuid_prefix = $namespaced_primary_key_uuid . '\\';
     $namespaced_key = $namespaced_primary_key_uuid_prefix . $sub_key;
     if (isset($namespaced_key[251])) {
         throw $this->c::issue(sprintf('Sub key too long; %1$s bytes max.', 250 - strlen($namespaced_primary_key_uuid_prefix)));
     }
     return $namespaced_key;
 }
Ejemplo n.º 26
0
 /**
  *
  *
  * @param string $key
  * @param mixed $value
  * @param array $options
  * @return bool
  */
 public function add($key, $value, $options = array())
 {
     if (!$this->online()) {
         return Gdn_Cache::CACHEOP_FAILURE;
     }
     $finalOptions = array_merge($this->StoreDefaults, $options);
     $expiry = val(Gdn_Cache::FEATURE_EXPIRY, $finalOptions, 0);
     $useLocal = (bool) $finalOptions[Gdn_Cache::FEATURE_LOCAL];
     $realKey = $this->makeKey($key, $finalOptions);
     // Sharding, write real keys
     if (array_key_exists(Gdn_Cache::FEATURE_SHARD, $finalOptions) && ($shards = $finalOptions[Gdn_Cache::FEATURE_SHARD])) {
         $manifest = $this->shard($realKey, $value, $shards);
         $shards = $manifest->shards;
         unset($manifest->shards);
         // Attempt to write manifest
         $added = $this->memcache->add($realKey, $manifest, $expiry);
         // Check if things went ok
         $ok = $this->lastAction($realKey);
         if (!$ok || !$added) {
             return Gdn_Cache::CACHEOP_FAILURE;
         }
         // Write real keys
         foreach ($shards as $shard) {
             $this->memcache->setByKey($shard['server'], $shard['key'], $shard['data'], $expiry);
         }
         unset($shards);
         if ($useLocal) {
             $this->localSet($realKey, $value);
         }
         return Gdn_Cache::CACHEOP_SUCCESS;
     }
     $stored = $this->memcache->add($realKey, $value, $expiry);
     // Check if things went ok
     $ok = $this->lastAction($realKey);
     if (!$ok) {
         return Gdn_Cache::CACHEOP_FAILURE;
     }
     if ($stored) {
         if ($useLocal) {
             $this->localSet($realKey, $value);
         }
         return Gdn_Cache::CACHEOP_SUCCESS;
     }
     return Gdn_Cache::CACHEOP_FAILURE;
 }
Ejemplo n.º 27
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.º 28
0
 /**
  * construct wrapper
  *
  * @param \stdClass $param
  *
  * @return \chilimatic\lib\Cache\Engine\Memcached
  */
 public function __construct($param = null)
 {
     parent::__construct(isset($param->persistent_id) ? $param->persistent_id : null, isset($param->callback) ? $param->callback : null);
     if (isset($param->server_list)) {
         $server = $param->server_list;
         if (count($server) === 1) {
             $server = array_pop($server);
             $this->setConnected(parent::addServer($server->host, $server->port ?? self::DEFAULT_PORT, isset($server->weight) ? $server->weight : null));
         } else {
             $this->setConnected(parent::addServers($server));
         }
     }
     // Get the Cache Listing
     $this->cacheListing = parent::get('cacheListing');
     if ($this->cacheListing === false) {
         parent::add('cacheListing', array());
         $this->cacheListing = array();
     }
     // check sum for the saving process
     $this->md5Sum = md5(json_encode($this->cacheListing));
 }
Ejemplo n.º 29
0
 /**
  * Returns the name for the given cache name in respect to flush count.
  * 
  * @param	string		$cacheName
  * @return	string
  */
 protected function getCacheName($cacheName)
 {
     $parts = explode('-', $cacheName, 2);
     $flush = $this->memcached->get('_flush');
     // create flush counter if it does not exist
     if ($flush === false) {
         $this->memcached->add('_flush', TIME_NOW);
         $flush = $this->memcached->get('_flush');
     }
     // the cache specific flush counter only is of interest if the cache name contains parameters
     // the version without parameters is deleted explicitly when calling flush
     // this saves us a memcached query in most cases (caches without any parameters)
     if (isset($parts[1])) {
         $flushByCache = $this->memcached->get('_flush_' . $parts[0]);
         // create flush counter if it does not exist
         if ($flushByCache === false) {
             $this->memcached->add('_flush_' . $parts[0], TIME_NOW);
             $flushByCache = $this->memcached->get('_flush_' . $parts[0]);
         }
         $flush .= '_' . $flushByCache;
     }
     return $flush . '_' . $cacheName;
 }
Ejemplo n.º 30
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));
 }