Ejemplo n.º 1
0
 public function __construct()
 {
     $this->mem = new Memcached(static::$servers_id);
     if (count($this->mem->getServerList()) == 0) {
         $this->mem->addServer("", 11211);
     }
 }
Ejemplo n.º 2
0
 /**
  * @param array $servers List of servers
  * @param int $expire Expiration time, defaults to 3600 seconds
  * @throws \Exception
  */
 public function __construct($servers = [], $expire = 3600)
 {
     // Set expiration time
     $this->expire = $expire;
     // Create memcached object
     $this->cache = new \Memcached();
     // Check if there already are servers added, according to the manual
     // http://php.net/manual/en/memcached.addservers.php no duplication checks
     // are made. Since we have at least one connection we don't need to add
     // more servers and maybe add duplicates.
     if (count($this->cache->getServerList()) === 0) {
         // Add servers
         $this->cache->addServers($servers);
     }
     // Get server stats
     $stats = $this->cache->getStats();
     // Loop through servers
     foreach ($stats as $stat) {
         // Check if pid is more than 0, if pid is -1 connection isn't working
         if ($stat['pid'] > 0) {
             // Return true to avoid the exception below
             return true;
         }
     }
     // If we end up here we don't have a working connection. Throw an exception that
     // will be handled by the method calling this connect method. A working cache is
     // NOT a requirement for the application to run so it's important to handle the
     // exception and let the application run. Suggestion: if the exception below is
     // thrown a new NullCache should be created
     throw new \Exception('Unable to connect to Memcache(d) backend');
 }
 public function __construct($persistent = true)
 {
     /*
      * Caching can be disabled in the config file if you aren't able to run
      * a memcached instance.  In that case this class will still get used,
      * but we will pretend that we have a perpetually empty cache.
      */
     if (defined("USE_MEMCACHED") && USE_MEMCACHED != false) {
         $servers = null;
         if ($persistent === true) {
             /*
              * Since prefix should be unique across RTK installations, we can
              * use the server hostname + port + prefix as a persistent ID.
              * Hostname + port are included because otherwise changing the
              * memcached server would NOT change the persistent connection,
              * and you'd end up using the old server.
              */
             $persistentID = MEMCACHED_HOST . ":" . MEMCACHED_PORT . "_" . MEMCACHED_PREFIX;
             $this->cache = new Memcached($persistentID);
             $serverList = $this->cache->getServerList();
             foreach ($serverList as $entry) {
                 $servers[] = $entry['host'] . ":" . $entry['port'];
             }
         } else {
             //Not running Memcached in persistent mode.
             $this->cache = new Memcached();
         }
         if ($persistent !== true || !is_array($servers) || !in_array(MEMCACHED_HOST . ":" . MEMCACHED_PORT, $servers)) {
             $this->cache->addServer(MEMCACHED_HOST, MEMCACHED_PORT);
         }
     }
 }
Ejemplo n.º 4
0
 /**
  * Create the Memcached connection
  *
  * @return  void
  *
  * @since   12.1
  * @throws  RuntimeException
  */
 protected function getConnection()
 {
     if (!static::isSupported()) {
         throw new RuntimeException('Memcached Extension is not available');
     }
     $config = JFactory::getConfig();
     $host = $config->get('memcached_server_host', 'localhost');
     $port = $config->get('memcached_server_port', 11211);
     // Create the memcached connection
     if ($config->get('memcached_persist', true)) {
         static::$_db = new Memcached($this->_hash);
         $servers = static::$_db->getServerList();
         if ($servers && ($servers[0]['host'] != $host || $servers[0]['port'] != $port)) {
             static::$_db->resetServerList();
             $servers = array();
         }
         if (!$servers) {
             static::$_db->addServer($host, $port);
         }
     } else {
         static::$_db = new Memcached();
         static::$_db->addServer($host, $port);
     }
     static::$_db->setOption(Memcached::OPT_COMPRESSION, $this->_compress);
     $stats = static::$_db->getStats();
     $result = !empty($stats["{$host}:{$port}"]) && $stats["{$host}:{$port}"]['pid'] > 0;
     if (!$result) {
         // Null out the connection to inform the constructor it will need to attempt to connect if this class is instantiated again
         static::$_db = null;
         throw new JCacheExceptionConnecting('Could not connect to memcached server');
     }
 }
Ejemplo n.º 5
0
 /**
  * Construct the driver instance.
  *
  * @param Config $config The instance config
  */
 public function __construct(Config $config, Instance $instance)
 {
     $this->instance = $instance;
     $this->client = new \Memcached($config->name);
     if (count($this->client->getServerList()) === 0) {
         $this->client->addServers($config->servers->toArray());
     }
 }
 /**
  * @return array
  */
 protected function getMemcacheKeys()
 {
     $keys = [];
     foreach ($this->memcache->getServerList() as $server) {
         $keys = array_merge($keys, $this->getMemcacheKeysForHost($server[MemcacheConfigConstants::SERVER_HOST], $server[MemcacheConfigConstants::SERVER_PORT]));
     }
     return $keys;
 }
Ejemplo n.º 7
0
 public static function setUpBeforeClass()
 {
     self::$memcached = new \Memcached();
     self::$memcached->setOptions(array(\Memcached::OPT_TCP_NODELAY => true, \Memcached::OPT_NO_BLOCK => true, \Memcached::OPT_CONNECT_TIMEOUT => 1000));
     if (count(self::$memcached->getServerList()) == 0) {
         self::$memcached->addServers(array(array(MEMCACHED_HOST, MEMCACHED_PORT)));
     }
 }
Ejemplo n.º 8
0
 /**
  * Set connection
  *
  * @param \Memcached $memcached
  *
  * @return $this
  *
  */
 public function setConnection(\Memcached $memcached)
 {
     $this->connection = $memcached;
     if (!count($this->connection->getServerList())) {
         $this->configureServers();
     }
     $this->setOptions();
     return $this;
 }
Ejemplo n.º 9
0
 protected function _addServer($server, $port, $persist, $weight, $timeout)
 {
     $list = $this->_connection->getServerList();
     foreach ($list as $srv) {
         if ($srv['host'] === $server && (int) $srv['port'] === (int) $port && (!isset($srv['weight']) || (int) $srv['weight'] === (int) $weight)) {
             return;
         }
     }
     $this->_connection->addServer($server, $port, $weight);
 }
Ejemplo n.º 10
0
 /**
  * @param $server
  * @param $port
  * @param $userName
  * @param $password
  * @param $bucket
  */
 public function __construct($server, $port, $userName, $password, $bucket)
 {
     $this->_instance = new \Memcached();
     $this->_instance->setOption(\Memcached::SERIALIZER_JSON, TRUE);
     $this->_instance->setOption(\Memcached::OPT_COMPRESSION, FALSE);
     $this->_instance->setOption(\Memcached::OPT_CONNECT_TIMEOUT, 500);
     $this->_instance->setOption(\Memcached::OPT_POLL_TIMEOUT, 500);
     $this->_instance->setOption(\Memcached::OPT_TCP_NODELAY, TRUE);
     $this->_instance->setOption(\Memcached::OPT_NO_BLOCK, TRUE);
     if (!count($this->_instance->getServerList())) {
         $this->_instance->addServer($server, $port);
     }
 }
Ejemplo n.º 11
0
 /**
  * @param ConfigurationInterface $configuration
  */
 protected function __construct(ConfigurationInterface $configuration)
 {
     $this->configuration = $configuration;
     $this->cache = new \Memcached();
     $serverList = $this->cache->getServerList();
     if (empty($serverList)) {
         $this->cache->addServer($this->configuration->getHost(), $this->configuration->getPort());
     }
     $this->cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
     if ($this->configuration->shouldCheckConnection()) {
         $this->checkConnection();
     }
 }
Ejemplo n.º 12
0
 /**
  * Get Mamcached Handler
  *
  * @return \Memcached
  */
 public function getHandler()
 {
     if (!$this->handler) {
         $persistentId = isset($this->settings['persistent']) ? $this->settings['persistent'] : null;
         $this->handler = new \Memcached($persistentId);
         if (!$this->handler->getServerList()) {
             $this->handler->addServers($this->settings['servers']);
         }
         if (isset($this->settings['options'])) {
             $this->handler->setOptions($this->settings['options']);
         }
     }
     return $this->handler;
 }
Ejemplo n.º 13
0
 /**
  * Initialize the Cache Engine
  *
  * Called automatically by the cache frontend
  *
  * @param array $config array of setting for the engine
  * @return bool True if the engine has been successfully initialized, false if not
  * @throws \InvalidArgumentException When you try use authentication without
  *   Memcached compiled with SASL support
  */
 public function init(array $config = [])
 {
     if (!extension_loaded('memcached')) {
         return false;
     }
     $this->_serializers = ['igbinary' => Memcached::SERIALIZER_IGBINARY, 'json' => Memcached::SERIALIZER_JSON, 'php' => Memcached::SERIALIZER_PHP];
     if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) {
         $this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK;
     }
     parent::init($config);
     if (!empty($config['host'])) {
         if (empty($config['port'])) {
             $config['servers'] = [$config['host']];
         } else {
             $config['servers'] = [sprintf('%s:%d', $config['host'], $config['port'])];
         }
     }
     if (isset($config['servers'])) {
         $this->config('servers', $config['servers'], false);
     }
     if (!is_array($this->_config['servers'])) {
         $this->_config['servers'] = [$this->_config['servers']];
     }
     if (isset($this->_Memcached)) {
         return true;
     }
     if ($this->_config['persistent']) {
         $this->_Memcached = new Memcached((string) $this->_config['persistent']);
     } else {
         $this->_Memcached = new Memcached();
     }
     $this->_setOptions();
     if (count($this->_Memcached->getServerList())) {
         return true;
     }
     $servers = [];
     foreach ($this->_config['servers'] as $server) {
         $servers[] = $this->_parseServerString($server);
     }
     if (!$this->_Memcached->addServers($servers)) {
         return false;
     }
     if (is_array($this->_config['options'])) {
         foreach ($this->_config['options'] as $opt => $value) {
             $this->_Memcached->setOption($opt, $value);
         }
     }
     if (empty($this->_config['username']) && !empty($this->_config['login'])) {
         throw new InvalidArgumentException('Please pass "username" instead of "login" for connecting to Memcached');
     }
     if ($this->_config['username'] !== null && $this->_config['password'] !== null) {
         $sasl = method_exists($this->_Memcached, 'setSaslAuthData') && ini_get('memcached.use_sasl');
         if (!$sasl) {
             throw new InvalidArgumentException('Memcached extension is not build with SASL support');
         }
         $this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
         $this->_Memcached->setSaslAuthData($this->_config['username'], $this->_config['password']);
     }
     return true;
 }
Ejemplo n.º 14
0
 private function __construct()
 {
     if (defined('MEMCACHE_SERVERS')) {
         try {
             // create a new persistent client
             $m = new Memcached("memcached_pool");
             $m->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE);
             // some nicer default options
             $m->setOption(Memcached::OPT_NO_BLOCK, TRUE);
             $m->setOption(Memcached::OPT_AUTO_EJECT_HOSTS, TRUE);
             $m->setOption(Memcached::OPT_CONNECT_TIMEOUT, 2000);
             $m->setOption(Memcached::OPT_POLL_TIMEOUT, 2000);
             $m->setOption(Memcached::OPT_RETRY_TIMEOUT, 2);
             // setup authentication
             if (defined('MEMCACHE_USERNAME') && defined('MEMCACHE_PASSWORD')) {
                 $m->setSaslAuthData(MEMCACHE_USERNAME, MEMCACHE_PASSWORD);
             }
             // We use a consistent connection to memcached, so only add in the
             // servers first time through otherwise we end up duplicating our
             // connections to the server.
             if (!$m->getServerList()) {
                 // parse server config
                 $servers = explode(",", MEMCACHE_SERVERS);
                 foreach ($servers as $s) {
                     $parts = explode(":", $s);
                     $m->addServer($parts[0], $parts[1]);
                 }
             }
         } catch (Exception $e) {
             $this->objCache = false;
         }
     } else {
         $this->objCache = false;
     }
 }
Ejemplo n.º 15
0
 /**
  * Servers differ? i.e., current vs. active.
  *
  * @since 151216 Memcached utilities.
  *
  * @return bool True if servers differ.
  */
 protected function serversDiffer() : bool
 {
     if (!$this->Pool) {
         return false;
         // Not possible.
     }
     $active_servers = [];
     // Initialize array.
     foreach ($this->Pool->getServerList() as $_server) {
         $active_servers[$_server['host'] . ':' . $_server['port']] = $_server;
     }
     // unset($_server); // Housekeeping.
     if (count($this->servers) !== count($active_servers)) {
         return true;
         // They definitely differ.
     }
     foreach ($this->servers as $_key => $_server) {
         if (!isset($active_servers[$_key])) {
             return true;
         }
         // unset($_key, $_server);
     }
     foreach ($active_servers as $_key => $_server) {
         if (!isset($this->servers[$_key])) {
             return true;
         }
         // unset($_key, $_server);
     }
     return false;
 }
Ejemplo n.º 16
0
function check_login()
{
    global $db, $mem;
    if (defined('MEM') && MEM == True) {
        $mem = new Memcached('moyoj');
        $mem->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
        if (!count($mem->getServerList())) {
            $mem->addServer(MEM_HOST, MEM_PORT);
        }
    }
    $db = new DB();
    $db->init(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    $db->connect();
    $admin_info = mo_read_cache('mo-admin-' . $_SESSION['aid']);
    if (!$admin_info) {
        $sql = 'SELECT `id`, `username`, `password`, `nickname`, `role` FROM `mo_admin` WHERE `id` = ? AND `role` > 0';
        $db->prepare($sql);
        $db->bind('i', $_SESSION['aid']);
        $result = $db->execute();
        if (!$result || $result[0]['password'] != $_SESSION['admin_password']) {
            unset($_SESSION['aid']);
            header("Location: login.php");
            exit(0);
        }
        mo_write_cache('mo-admin-' . $_SESSION['aid'], $result[0]);
    }
    $mo_settings = array();
    mo_load_settings();
    if (!isset($active)) {
        $active = '';
    }
}
Ejemplo n.º 17
0
 /**
  * @inheritdoc
  */
 public function status()
 {
     $status_arr = $this->memcached->getStats();
     $server_arr = $this->memcached->getServerList();
     if (isset($server_arr[0]['host']) and isset($server_arr[0]['port']) and isset($status_arr["{$server_arr[0]['host']}:{$server_arr[0]['port']}"])) {
         $info = $status_arr["{$server_arr[0]['host']}:{$server_arr[0]['port']}"];
     } else {
         $info = [];
     }
     $status[self::HITS] = isset($info['get_hits']) ? $info['get_hits'] : 0;
     $status[self::MISSES] = isset($info['get_misses']) ? $info['get_misses'] : 0;
     $status[self::START_TIME] = isset($info['uptime']) ? $info['uptime'] : 0;
     $status[self::MEMORY_USED] = isset($info['bytes']) ? $info['bytes'] : 0;
     $status[self::MEMORY_LEFT] = isset($info['limit_maxbytes']) ? $info['limit_maxbytes'] : 0;
     return $status;
 }
Ejemplo n.º 18
0
 protected function __construct()
 {
     if (class_exists('\\Memcached')) {
         $m = new \Memcached("memcached_pool");
         $m->setOption(\Memcached::OPT_BINARY_PROTOCOL, TRUE);
         // some nicer default options
         $m->setOption(\Memcached::OPT_NO_BLOCK, TRUE);
         $m->setOption(\Memcached::OPT_AUTO_EJECT_HOSTS, TRUE);
         // We use a consistent connection to memcached, so only add in the
         // servers first time through otherwise we end up duplicating our
         // connections to the server.
         if (!$m->getServerList()) {
             // parse server config
             $servers = explode(",", MEMCACHE_SERVERS);
             foreach ($servers as $s) {
                 $parts = explode(":", $s);
                 $m->addServer($parts[0], $parts[1]);
             }
         }
         // setup authentication
         if (defined('MEMCACHE_USERNAME') && defined('MEMCACHE_PASSWORD')) {
             $m->setSaslAuthData(MEMCACHE_USERNAME, MEMCACHE_PASSWORD);
         }
         $this->memcache = $m;
     }
 }
Ejemplo n.º 19
0
 protected function __construct($config)
 {
     if (empty($config)) {
         throw new \exception('invalid!');
     }
     $c = new \Memcached('sk_cache');
     //$c->resetserverlist();
     $config_servers = $config['servers'];
     //easier to keep the code straight this way.
     $used_servers = $c->getServerList();
     $count_servers_used = count($used_servers);
     $count_servers_config = count($config_servers);
     if (!$count_servers_used) {
         //we have no servers stored. store the entire array.
         $c->addServers($config_servers);
     } else {
         //we need to check to see if a new server was added to the config.
         if ($count_servers_used < $count_servers_config) {
             $used = array_column($used_servers, 0);
             //0 index is ip, 1 index is port...
             $config = array_column($config_servers, 0);
             usort($used, ['self', 'sortServers']);
             usort($config, ['self', 'sortServers']);
             $diff = $count_servers_config - $count_servers_used;
             $new = array_slice($config, $count_servers_used - 1);
             foreach ($new as $server) {
                 $c->addServer($server, 11211);
                 //to do: find a way to retrieve the port of the server when adding it, in case of people with custom ports for memcache.
             }
         }
     }
     $this->driver = $c;
     self::$instance =& $this;
 }
Ejemplo n.º 20
0
 /**
  * Open
  *
  * Sanitizes save_path and initializes connections.
  *
  * @param    string $save_path Server path(s)
  * @param    string $name Session cookie name, unused
  * @return    bool
  */
 public function open($save_path, $name)
 {
     $this->_memcached = new Memcached();
     $this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE);
     // required for touch() usage
     $server_list = array();
     foreach ($this->_memcached->getServerList() as $server) {
         $server_list[] = $server['host'] . ':' . $server['port'];
     }
     if (!preg_match_all('#,?([^,:]+)\\:(\\d{1,5})(?:\\:(\\d+))?#', $this->_config['save_path'], $matches, PREG_SET_ORDER)) {
         $this->_memcached = NULL;
         log_message('error', 'Session: Invalid Memcached save path format: ' . $this->_config['save_path']);
         return FALSE;
     }
     foreach ($matches as $match) {
         // If Memcached already has this server (or if the port is invalid), skip it
         if (in_array($match[1] . ':' . $match[2], $server_list, TRUE)) {
             log_message('debug', 'Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]);
             continue;
         }
         if (!$this->_memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0)) {
             log_message('error', 'Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.');
         } else {
             $server_list[] = $match[1] . ':' . $match[2];
         }
     }
     if (empty($server_list)) {
         log_message('error', 'Session: Memcached server pool is empty.');
         return FALSE;
     }
     return TRUE;
 }
Ejemplo n.º 21
0
 /**
  * Open
  *
  * Sanitizes save_path and initializes connections.
  *
  * @param    string $save_path Server path(s)
  * @param    string $name      Session cookie name, unused
  *
  * @return    bool
  */
 public function open($save_path, $name)
 {
     $this->memcached = new \Memcached();
     $this->memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
     // required for touch() usage
     $server_list = [];
     foreach ($this->memcached->getServerList() as $server) {
         $server_list[] = $server['host'] . ':' . $server['port'];
     }
     if (!preg_match_all('#,?([^,:]+)\\:(\\d{1,5})(?:\\:(\\d+))?#', $this->savePath, $matches, PREG_SET_ORDER)) {
         $this->memcached = null;
         $this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);
         return false;
     }
     foreach ($matches as $match) {
         // If Memcached already has this server (or if the port is invalid), skip it
         if (in_array($match[1] . ':' . $match[2], $server_list, true)) {
             $this->logger->debug('Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]);
             continue;
         }
         if (!$this->memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0)) {
             $this->logger->error('Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.');
         } else {
             $server_list[] = $match[1] . ':' . $match[2];
         }
     }
     if (empty($server_list)) {
         $this->logger->error('Session: Memcached server pool is empty.');
         return false;
     }
     return true;
 }
Ejemplo n.º 22
0
 /**
  * 生成Memcached实例
  *
  * @param array  $serverList
  * @param string $persistentId 持久连接的名称
  * @return \Memcached
  */
 public static function memcached(array $serverList, $persistentId = '')
 {
     $saver = new \Memcached($persistentId);
     if (!count($saver->getServerList())) {
         $saver->addServers($serverList);
     }
     return $saver;
 }
Ejemplo n.º 23
0
 /**
  * @Name: add_server
  *
  * @param
  *            :none
  * @todu 连接memcache server
  * @return : TRUE or FALSE
  *         add by cheng.yafei
  *
  */
 public function add_server($server)
 {
     if (count($this->m->getServerList()) == 0) {
         extract($server);
         return $this->m->addServer($host, $port, $weight);
     }
     return true;
 }
Ejemplo n.º 24
0
 /**
  * This method cannot be overridden because you need to override \Hoard\AbstractPool::getAdapterOptions().
  *
  * @return \Memcached
  * @throws \Exception
  */
 protected final function getConnection()
 {
     $defaultPersistentId = 'hoard-persist';
     // first time connect
     if (null == $this->connection) {
         if (!class_exists('\\Memcached')) {
             throw new \Exception('Memcached extension is not installed.');
         }
         $this->connection = new \Memcached($defaultPersistentId);
         if (!count($this->connection->getServerList())) {
             // setup memcached options
             if (isset($this->adapterOptions['client']) && is_array($this->adapterOptions['client'])) {
                 foreach ($this->adapterOptions['client'] as $name => $value) {
                     $optId = null;
                     if (is_int($name)) {
                         $optId = $name;
                     } else {
                         $optConst = 'Memcached::OPT_' . strtoupper($name);
                         if (defined($optConst)) {
                             $optId = constant($optConst);
                         } else {
                             throw new \Exception("Unknown memcached client option '{$name}' ({$optConst})");
                         }
                     }
                     if (null !== $optId) {
                         if (!$this->connection->setOption($optId, $value)) {
                             throw new \Exception("Setting memcached client option '{$optId}' failed");
                         }
                     }
                 }
             }
             // if no servers are provided try to bind to default configuration
             if (!array_key_exists('servers', $this->adapterOptions)) {
                 $this->adapterOptions['servers'] = array('localhost:11211');
             }
             // add servers
             foreach ($this->adapterOptions['servers'] as $server) {
                 list($host, $port) = explode(':', $server, 2);
                 $this->connection->addServer($host, $port);
             }
         }
     }
     return $this->connection;
 }
Ejemplo n.º 25
0
 /**
  * @param array $servers
  * @param string $persistentId
  * @return \Memcached
  */
 public static function get(array $servers, $persistentId = null)
 {
     $memcached = new \Memcached($persistentId);
     if (!count($memcached->getServerList())) {
         foreach ($servers as $server) {
             $memcached->addServer($server['host'], $server['port']);
         }
     }
     return $memcached;
 }
Ejemplo n.º 26
0
 /**
  * Detect if backend is available
  * @return bool
  */
 public static function isAvailable()
 {
     try {
         if (!extension_loaded('memcached')) {
             return false;
         }
         if (self::$memcache) {
             return true;
         }
         self::$memcache = new \MemCached();
         $currentServers = self::$memcache->getServerList();
         if (empty($currentServers)) {
             return false;
         }
         return true;
     } catch (Exception $ex) {
         return false;
     }
 }
 protected function init()
 {
     if (!self::$memcached) {
         if (!empty($this->options['persistent'])) {
             self::$memcached = new Memcached($this->options['persistent']);
             // if servers already exists
             if (self::$memcached->getServerList()) {
                 return;
             }
         } else {
             self::$memcached = new Memcached();
         }
         if (empty($this->options['servers'])) {
             self::$memcached->addServer('127.0.0.1', 11211);
         } else {
             foreach ($this->options['servers'] as $s) {
                 self::$memcached->addServer($s['host'], isset($s['port']) ? $s['port'] : 11211, isset($s['weight']) ? $s['weight'] : 0);
             }
         }
     }
 }
Ejemplo n.º 28
0
 /**
  * Add a Memcached server to stack
  *
  * @param   string          $server         Server address (or IP)
  * @param   string          $port           Server port
  * @param   string          $weight         Server weight
  */
 private function addServer($server, $port, $weight)
 {
     $status = $this->instance->addServer($server, $port, $weight);
     if ($status === false) {
         $this->raiseError("Error communicating with server", array("RESULTCODE" => $this->instance->getResultCode(), "RESULTMESSAGE" => $this->instance->getResultMessage()));
     }
     if (sizeof($this->instance->getServerList()) == 0) {
         $this->raiseError("No available server, disabling cache administratively");
         $this->disable();
     } else {
         $this->enable();
     }
 }
Ejemplo n.º 29
0
 public function addMemcachedServers(\Memcached $cache, $servers)
 {
     $existingServers = array();
     if ($this->persistentId !== null) {
         foreach ($cache->getServerList() as $s) {
             $existingServers[$s['host'] . ':' . $s['port']] = true;
         }
     }
     foreach ($servers as $server) {
         if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) {
             $cache->addServer($server->host, $server->port, $server->weight);
         }
     }
 }
Ejemplo n.º 30
0
 /**
  * Initialises the cache.
  *
  * Once this has been done the cache is all set to be used.
  *
  * @param cache_definition $definition
  */
 public function initialise(cache_definition $definition)
 {
     if ($this->is_initialised()) {
         throw new coding_exception('This memcached instance has already been initialised.');
     }
     $this->definition = $definition;
     $this->connection = new Memcached(crc32($this->name));
     $servers = $this->connection->getServerList();
     if (empty($servers)) {
         foreach ($this->options as $key => $value) {
             $this->connection->setOption($key, $value);
         }
         $this->connection->addServers($this->servers);
     }
 }