예제 #1
0
 /**
  * Set/add something to the cache
  *
  * @param  string $key Key for the value
  * @param  mixed  $value Value
  * @return boolean
  */
 public function set($key, $value)
 {
     if ($this->cache->add($key, $value, $this->compression, $this->expire)) {
         return true;
     }
     return $this->cache->replace($key, $value, $this->compression, $this->expire);
 }
예제 #2
0
 /**
  * Save getting data to memory (RAM)
  */
 public function save()
 {
     $this->storage_data['last_update'] = $this->last_update;
     if ($this->memcache->replace('storage_data', $this->storage_data) === false) {
         $this->memcache->add('storage_data', $this->storage_data);
     }
 }
예제 #3
0
 /**
  * @param string $id - session id, must be valid hash
  * @return string
  */
 public static function read($id)
 {
     if (!self::isConnected() || !self::isValidId($id)) {
         return "";
     }
     $sid = self::getPrefix();
     if (!self::$isReadOnly) {
         $lockTimeout = 55;
         //TODO: add setting
         $lockWait = 59000000;
         //micro seconds = 60 seconds TODO: add setting
         $waitStep = 100;
         while (!self::$connection->add($sid . $id . ".lock", 1, 0, $lockTimeout)) {
             usleep($waitStep);
             $lockWait -= $waitStep;
             if ($lockWait < 0) {
                 CSecuritySession::triggerFatalError('Unable to get session lock within 60 seconds.');
             }
             if ($waitStep < 1000000) {
                 $waitStep *= 2;
             }
         }
     }
     self::$sessionId = $id;
     $res = self::$connection->get($sid . $id);
     if ($res === false) {
         $res = "";
     }
     return $res;
 }
예제 #4
0
 function add($key, $value, $ttl = 0)
 {
     $key = str_replace('\\', '/', $key);
     if (!$this->memcache->add($key, $value, false, $ttl)) {
         $message = sprintf('Memcache::set() with key "%s" failed', $key);
         \ManiaLib\Utils\Logger::error($message);
     }
 }
예제 #5
0
 public function add($id, $value, $ttl = null)
 {
     $ttl = $ttl ?: 0;
     if ($ttl > 0) {
         $ttl = time() + $ttl;
     }
     return $this->memcache->add($id, $value, 0, $ttl);
 }
예제 #6
0
 public function exists($id)
 {
     $success = $this->memcache->add($id, 0);
     if (!$success) {
         return true;
     }
     $this->memcache->delete($id);
     return false;
 }
예제 #7
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(), null, $expiry)) {
         if (!$this->isLocked($mutexKey)) {
             throw new LockFailedException();
         }
     }
 }
예제 #8
0
 public function store($key, $value, $overwrite, $ttl = 0)
 {
     // always store as an UNIX timestamp
     // (see description of the expire parameter in the PHP manunal)
     $expire = $ttl > 0 ? time() + $ttl : 0;
     if ($overwrite) {
         return $this->memcache->set($key, $value, 0, $expire);
     } else {
         return $this->memcache->add($key, $value, 0, $expire);
     }
 }
예제 #9
0
 /**
  * 设置缓存
  *
  * @param string $key 要设置的缓存项目名称
  * @param mixed $value 要设置的缓存项目内容
  * @param int $time 要设置的缓存项目的过期时长,默认保存时间为 -1,永久保存为 0
  *
  * @return bool 保存是成功为true ,失败为false
  */
 public function store($key, $value, $time = -1)
 {
     if ($time == -1) {
         $time = $this->expire;
     }
     $sValue = serialize($value);
     if (!$this->connection->add($key, $sValue, $this->compressed, $time)) {
         return $this->connection->set($key, $sValue, $this->compressed, $time);
     }
     return true;
 }
예제 #10
0
 function keyExists($key)
 {
     if (null === $this->memcache) {
         $this->connect();
     }
     if ($this->memcache->add($key, null)) {
         $this->memcache->delete($key);
         return false;
     } else {
         return true;
     }
 }
예제 #11
0
	/**
	 * @param string $id - session id, must be valid hash
	 * @return string
	 */
	public static function read($id)
	{
		if(!self::isConnected() || !self::isValidId($id))
			return "";

		$sid = self::getPrefix();

		if (!self::$isReadOnly)
		{
			$lockTimeout = 55;//TODO: add setting
			$lockWait = 59000000;//micro seconds = 60 seconds TODO: add setting
			$waitStep = 100;

			if (defined('BX_SECURITY_SESSION_MEMCACHE_EXLOCK') && BX_SECURITY_SESSION_MEMCACHE_EXLOCK)
				$lock = Bitrix\Main\Context::getCurrent()->getRequest()->getRequestedPage();
			else
				$lock = 1;

			while(!self::$connection->add($sid.$id.".lock", $lock, 0, $lockTimeout))
			{
				usleep($waitStep);
				$lockWait -= $waitStep;
				if($lockWait < 0)
				{
					$errorText = 'Unable to get session lock within 60 seconds.';
					if ($lock !== 1)
					{
						$lockedUri = self::$connection->get($sid.$id.".lock");
						if ($lockedUri && $lockedUri != 1)
							$errorText .= sprintf(' Locked by "%s".', self::$connection->get($sid.$id.".lock"));
					}

					CSecuritySession::triggerFatalError($errorText);
				}

				if($waitStep < 1000000)
					$waitStep *= 2;
			}
		}

		self::$sessionId = $id;
		self::$isSessionReady = true;
		$res = self::$connection->get($sid.$id);
		if($res === false)
			$res = "";

		return $res;
	}
예제 #12
0
 /**
  * Obtain lock on a key.
  *
  * @param string $key  The key to lock.
  */
 public function lock($key)
 {
     $i = 0;
     while ($this->_memcache->add($this->_key($key . self::LOCK_SUFFIX), 1, 0, self::LOCK_TIMEOUT) === false) {
         usleep(min(pow(2, $i++) * 10000, 100000));
     }
     /* Register a shutdown handler function here to catch cases where PHP
      * suffers a fatal error. Must be done via shutdown function, since
      * a destructor will not be called in this case.
      * Only trigger on error, since we must assume that the code that
      * locked will also handle unlocks (which may occur in the destruct
      * phase, e.g. session handling).
      * @todo: $this is not usable in closures until PHP 5.4+ */
     if (empty($this->_locks)) {
         $self = $this;
         register_shutdown_function(function () use($self) {
             $e = error_get_last();
             if ($e['type'] & E_ERROR) {
                 /* Try to do cleanup at very end of shutdown methods. */
                 register_shutdown_function(array($self, 'shutdown'));
             }
         });
     }
     $this->_locks[$key] = true;
 }
예제 #13
0
파일: shared.php 프로젝트: ntulip/TwitApps
function cache($op, $key, $val = '', $expiry = 604800)
{
    static $memcache = false;
    if ($memcache === false) {
        $memcache = new Memcache();
        $memcache->connect('localhost', 11211) or die('Fatal error - could not connect to Memcache');
    }
    $retval = true;
    // Prefix the key to avoid collisions with other apps
    $key = 'twitapps_' . $key;
    switch ($op) {
        case 'set':
            $memcache->set($key, $val, false, $expiry) or die('Fatal error - could not store ' . htmlentities($key) . ' in Memcache');
            break;
        case 'get':
            $retval = $memcache->get($key);
            break;
        case 'inc':
            $retval = $memcache->increment($key);
            break;
        case 'add':
            $retval = $memcache->add($key, $val, false, $expiry);
            break;
    }
    return $retval;
}
예제 #14
0
	/**
	 * Lock cache index
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   11.1
	 */
	protected function lockindex()
	{
		$looptime = 300;
		$data_lock = self::$_db->add($this->_hash . '-index_lock', 1, false, 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, false, 30);
				$lock_counter++;
			}
		}

		return true;
	}
예제 #15
0
 /**
  * 批量设置键值(当键名不存在时);<br>
  * 只有当键值全部设置成功时,才返回true,否则返回false并尝试回滚
  * @param array $sets   键值数组
  * @return boolean      是否成功
  */
 public function mSetNX($sets)
 {
     try {
         $keys = [];
         $status = true;
         foreach ($sets as $key => $value) {
             $value = self::setValue($value);
             $status = $this->handler->add($key, $value, $this->compress($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;
 }
예제 #16
0
 /**
  * Write data for key into cache if it doesn't exist already. When using memcached as your cache engine
  * remember that the Memcached PECL extension does not support cache expiry times greater
  * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  * If it already exists, it fails and returns false.
  *
  * @param string $key Identifier for the data.
  * @param mixed $value Data to be cached.
  * @param int $duration How long to cache the data, in seconds.
  * @return bool True if the data was successfully cached, false on failure.
  * @link http://php.net/manual/en/memcache.add.php
  */
 public function add($key, $value, $duration)
 {
     if ($duration > 30 * DAY) {
         $duration = 0;
     }
     return $this->_Memcache->add($key, $value, $this->settings['compress'], $duration);
 }
예제 #17
0
 /**
  * Write data for key into cache if it doesn't exist already. When using memcached as your cache engine
  * remember that the Memcached pecl extension does not support cache expiry times greater
  * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  * If it already exists, it fails and returns false.
  *
  * @param string $key Identifier for the data.
  * @param mixed $value Data to be cached.
  * @param int $duration How long to cache the data, in seconds.
  * @return bool True if the data was successfully cached, false on failure.
  * @link http://php.net/manual/en/memcached.add.php
  */
 public function add($key, $value, $duration)
 {
     if ($duration > 30 * DAY) {
         $duration = 0;
     }
     return $this->_Memcached->add($key, $value, $duration);
 }
예제 #18
0
파일: Memcache.php 프로젝트: horde/horde
 /**
  * Small wrapper around Memcache[d]#add().
  *
  * @param string $key  The key to lock.
  */
 protected function _lockAdd($key)
 {
     if ($this->_memcache instanceof Memcached) {
         $this->_memcache->add($this->_key($key . self::LOCK_SUFFIX), 1, self::LOCK_TIMEOUT);
     } else {
         $this->_memcache->add($this->_key($key . self::LOCK_SUFFIX), 1, 0, self::LOCK_TIMEOUT);
     }
 }
예제 #19
0
 /**
  * Obtain lock on a key.
  *
  * @param string $key  The key to lock.
  */
 public function lock($key)
 {
     $i = 0;
     while ($this->_memcache->add($this->_key($key . self::LOCK_SUFFIX), 1, 0, self::LOCK_TIMEOUT) === false) {
         usleep(min(pow(2, $i++) * 10000, 100000));
     }
     $this->_locks[$key] = true;
 }
예제 #20
0
 public function add($key, $var, $flag = 1, $expire = 0)
 {
     if (!$this->is_open) {
         return false;
     }
     $key = $this->format_key($key);
     return parent::add($key, $var, $flag, $expire);
 }
예제 #21
0
function addToCache($key, $content)
{
    $ini = parse_ini_file('scielo.def', true);
    $memcache = new Memcache();
    $memcache->connect($ini['CACHE']['SERVER_CACHE'], $ini['CACHE']['SERVER_PORT_CACHE']);
    $result = $memcache->add($key, $content);
    $memcache->close();
    return $result;
}
예제 #22
0
 /**
  * Store some data in session.
  * Expects a session id and the data to write.
  * @param string $sessionId
  * @param mixed $data
  * @return boolean
  */
 public function write($sessionId = '', $data = '')
 {
     if ($sessionId !== '') {
         if ($this->_memcache->replace($this->_key($sessionId), $data, null, $this->_lifetime) === false) {
             // add the item if we couldn't have replaced it (i.e. if it doesn't already exists)
             $this->_memcache->add($this->_key($sessionId), $data, null, $this->_lifetime);
         }
     }
     return true;
 }
 /**
  * This method will be called after a Datastore put.
  */
 protected function onItemWrite()
 {
     $mc = new Memcache();
     try {
         $key = self::getCacheKey($this->subscriber_url);
         $mc->add($key, $this, 0, 120);
     } catch (Google_Cache_Exception $ex) {
         syslog(LOG_WARNING, "in onItemWrite: memcache exception");
     }
 }
예제 #24
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;
}
예제 #25
0
 public function add($key, $var, $flag = null, $expire = null)
 {
     if ($this->stopwatch) {
         $e = $this->getStopwatchEvent('add');
     }
     $result = parent::add($key, $var, $flag, $expire);
     if ($this->stopwatch) {
         $e->stop();
     }
     return $result;
 }
예제 #26
0
파일: Data.php 프로젝트: nesbert/nobjects
 /**
  * Check if a key exists.
  *
  * @param $key
  * @return bool
  */
 public function exists($key)
 {
     if ($this->open()) {
         // if array check each key
         if (is_array($key)) {
             $out = array();
             foreach ($key as $k) {
                 if ($this->exists($k)) {
                     $out[$k] = true;
                 }
             }
             return $out;
         } elseif (empty($key)) {
             return false;
         }
         // try adding if true it does not exists
         if ($return = $this->memcache->add($key, 1)) {
             $this->memcache->delete($key, 0);
         }
         return $return === false;
     }
     return false;
 }
예제 #27
0
 /**
  * @param $keyword
  * @param string $value
  * @param int $time
  * @param array $option
  * @return array|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['skipExisting']) && $option['skipExisting'] == true) {
         return $this->instant->add($keyword, $value, false, $time);
     } else {
         return $this->instant->set($keyword, $value, false, $time);
     }
 }
예제 #28
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;
}
예제 #29
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->memcache->add($this->getKeyString($key), $value, $this->getFlagFromValue($value), $ttl);
         // @codeCoverageIgnoreStart
     } catch (\Exception $e) {
     }
     return false;
     // @codeCoverageIgnoreEnd
 }
예제 #30
0
 function add($key, $var, $flag = null, $expire = null, $mysql = false)
 {
     if (!$this->isConnected) {
         $this->connect();
     }
     if ($this->debugMode && !$mysql) {
         $s = get_microtime();
     }
     $return = parent::add($key, $var, $flag, $expire);
     if ($this->debugMode && !$mysql) {
         $e = get_microtime();
         array_push($this->queryLog, array('query' => 'add ' . $key, 'time' => number_format(($e - $s) * 1000, 4)));
     }
     return $return;
 }