Ejemplo n.º 1
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.º 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');
 }
Ejemplo n.º 3
0
 /**
  * @return bool
  */
 protected function checkConnection()
 {
     $stats = $this->cache->getStats();
     $result = isset($stats[$this->configuration->getHost() . ":" . $this->configuration->getPort()]);
     if (!$result) {
         throw new CacheException('Connection error!');
     }
     return true;
 }
Ejemplo n.º 4
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;
 }
 private function skipIfMemcacheIsNotRunning(\Memcached $client)
 {
     $memcacheAddress = self::MEMCACHED_HOST . ':' . self::MEMCACHED_PORT;
     if (!isset($client->getStats()[$memcacheAddress])) {
         $this->markTestSkipped('You need a running memcached to run the integration tests!');
     }
 }
Ejemplo n.º 6
0
 /**
  * Get available space in bytes
  *
  * @return int|float
  */
 public function getAvailableSpace()
 {
     $stats = $this->memcached->getStats();
     if ($stats === false) {
         throw new Exception\RuntimeException($this->memcached->getResultMessage());
     }
     $mem = array_pop($stats);
     return $mem['limit_maxbytes'] - $mem['bytes'];
 }
Ejemplo n.º 7
0
 /**
  * Internal method to get storage capacity.
  *
  * @param  array $normalizedOptions
  * @return array|boolean Capacity as array or false on failure
  * @throws Exception\ExceptionInterface
  */
 protected function internalGetCapacity(array &$normalizedOptions)
 {
     $stats = $this->memcached->getStats();
     if ($stats === false) {
         throw $this->getExceptionByResultCode($this->memcached->getResultCode());
     }
     $mem = array_pop($stats);
     return array('free' => $mem['limit_maxbytes'] - $mem['bytes'], 'total' => $mem['limit_maxbytes']);
 }
Ejemplo n.º 8
0
 /**
  * Get cache server statistics.
  *
  * @return array|string
  * @access public
  */
 public function serverStatistics()
 {
     if ($this->connected === true && $this->ping() === true) {
         if ($this->isRedis === true) {
             return $this->server->info();
         } else {
             return $this->server->getStats();
         }
     }
     return array();
 }
Ejemplo n.º 9
0
 public function getStats($config)
 {
     if (!$config) {
         return array();
     }
     $memcached = new \Memcached();
     $memcached->setOption($memcached::OPT_PREFIX_KEY, $config['options']['namespace']);
     $memcached->addServers($config['options']['servers']);
     $stats = $memcached->getStats();
     return $stats;
 }
Ejemplo n.º 10
0
 /**
  * Get cache status
  *
  * @return  array
  */
 public function status()
 {
     if (!$this->isEnabled()) {
         return array("provider" => "memcached", "enabled" => false, "objects" => null, "options" => array());
     }
     $stats = $this->instance->getStats();
     $objects = 0;
     foreach ($stats as $key => $value) {
         $objects = max($objects, $value['curr_items']);
     }
     return array("provider" => "memcached", "enabled" => $this->isEnabled(), "objects" => intval($objects), "options" => $stats);
 }
Ejemplo n.º 11
0
 /**
  * 获取服务器池的统计信息
  * @param string $type
  * @return array|bool
  */
 public function getStats($type = "items")
 {
     switch ($this->client_type) {
         case 'Memcache':
             $stats = $this->m->getStats($type);
             break;
         default:
         case 'Memcached':
             $stats = $this->m->getStats();
             break;
     }
     return $stats;
 }
Ejemplo n.º 12
0
 public function setUp()
 {
     if (!extension_loaded('memcached')) {
         $this->markTestSkipped("Memcached extension not loaded");
     }
     // Ensure the proper configuration exists
     $config = new \r8\Test\Config("MEMCACHE", array("HOST", "PORT"));
     $config->test();
     $cache = new \Memcached();
     $cache->addServer(MEMCACHE_HOST, MEMCACHE_PORT);
     if ($cache->getStats() === FALSE) {
         $this->markTestSkipped("Unable to connect to Memcached server");
     }
 }
Ejemplo n.º 13
0
 /**
  * Get cache server statistics.
  *
  * @return array
  * @access public
  */
 public function serverStatistics()
 {
     if ($this->ping()) {
         switch (NN_CACHE_TYPE) {
             case self::TYPE_REDIS:
                 return $this->server->info();
             case self::TYPE_MEMCACHED:
                 return $this->server->getStats();
             case self::TYPE_APC:
                 return apc_cache_info();
         }
     }
     return array();
 }
Ejemplo n.º 14
0
 public function getMemcached()
 {
     try {
         $m = new \Memcached();
         $m->addServer(self::HOST, self::PORT);
         $stats = $m->getStats();
         $host = self::HOST . ':' . self::PORT;
         if ($stats[$host]['pid'] == -1) {
             throw new \Exception(sprintf('Unable to reach a memcached server on %s', $host));
         }
     } catch (\Exception $e) {
         $this->markTestSkipped($e->getMessage());
     }
     return $m;
 }
Ejemplo n.º 15
0
 /**
  * Get storage capacity.
  *
  * @param  array $options
  * @return array|boolean Capacity as array or false on failure
  *
  * @triggers getCapacity.pre(PreEvent)
  * @triggers getCapacity.post(PostEvent)
  * @triggers getCapacity.exception(ExceptionEvent)
  */
 public function getCapacity(array $options = array())
 {
     $args = new ArrayObject(array('options' => &$options));
     try {
         $eventRs = $this->triggerPre(__FUNCTION__, $args);
         if ($eventRs->stopped()) {
             return $eventRs->last();
         }
         $mem = array_pop($this->memcached->getStats());
         $result = array('free' => $mem['limit_maxbytes'] - $mem['bytes'], 'total' => $mem['limit_maxbytes']);
         return $this->triggerPost(__FUNCTION__, $args, $result);
     } catch (\Exception $e) {
         return $this->triggerException(__FUNCTION__, $args, $e);
     }
 }
Ejemplo n.º 16
0
 /**
  * 检查连接状态
  * @return boolean
  */
 public function checkDriver()
 {
     if (!$this->isConnected && $this->reConnected < $this->maxReConnected) {
         if ($this->handler->getStats() !== false) {
             $this->isConnected = true;
         } else {
             $this->handler->initServers();
         }
         if (!$this->isConnected) {
             $this->reConnected++;
         } else {
             $this->reConnected = 0;
         }
     }
     return $this->isConnected;
 }
Ejemplo n.º 17
0
 public function getStats()
 {
     $stats = $this->handler->getStats();
     $servers = $this->servers;
     foreach ($stats as $key => $stat) {
         if ($stat['pid'] === -1) {
             //移除不可用的server
             unset($servers[$key]);
         }
     }
     //没有可用的server
     if (empty($servers)) {
         $this->isConnected = false;
         return false;
     } else {
         $this->handler->resetServerList();
         $status = $this->handler->addServers(array_values($servers));
         if ($status) {
             $this->isConnected = true;
         }
         return $status;
     }
 }
Ejemplo n.º 18
0
 /**
  * @inheritdoc
  */
 public function info()
 {
     return $this->driver->getStats();
 }
Ejemplo n.º 19
0
 private function fetchStatus()
 {
     if ($this->isAvailable() && null !== self::$Server && empty($this->Status)) {
         $this->Status = self::$Server->getStats();
     }
 }
Ejemplo n.º 20
0
    $config['dp_autocreate'] = $config['cdp_autocreate'];
}
if (!isset($config['mibdir'])) {
    $config['mibdir'] = $config['install_dir'] . '/mibs';
}
$config['mib_dir'] = $config['mibdir'];
// If we're on SSL, let's properly detect it
if (isset($_SERVER['HTTPS'])) {
    $config['base_url'] = preg_replace('/^http:/', 'https:', $config['base_url']);
}
if ($config['memcached']['enable'] === true) {
    if (class_exists('Memcached')) {
        $memcache = new Memcached();
        $memcache->addServer($config['memcached']['host'], $config['memcached']['port']);
        if ($debug) {
            print_r($memcache->getStats());
        }
    } else {
        echo "WARNING: You have enabled memcached but have not installed the PHP bindings. Disabling memcached support.\n";
        echo "Try 'apt-get install php5-memcached' or 'pecl install memcached'. You will need the php5-dev and libmemcached-dev packages to use pecl.\n\n";
        $config['memcached']['enable'] = 0;
    }
}
// Set some times needed by loads of scripts (it's dynamic, so we do it here!)
$config['time']['now'] = time();
$config['time']['now'] -= $config['time']['now'] % 300;
$config['time']['fourhour'] = $config['time']['now'] - 14400;
// time() - (4 * 60 * 60);
$config['time']['sixhour'] = $config['time']['now'] - 21600;
// time() - (6 * 60 * 60);
$config['time']['twelvehour'] = $config['time']['now'] - 43200;
Ejemplo n.º 21
0
 /**
  * 获取服务器统计信息
  *
  * @return array
  */
 public function stat()
 {
     return $this->memcached ? $this->memcached->getStats() : null;
 }
Ejemplo n.º 22
0
    if ($is_admin) {
        $redis = new Redis();
        $redis->connect(CMW_REDIS_HOST);
        $info = $redis->info('default');
        $response['redis_version'] = $info['redis_version'];
        $response['redis_uptime'] = time_offset() + intval($info['uptime_in_seconds']);
        $redis->close();
    }
}
// Memcached //
if (defined('CMW_USING_MEMCACHED') && $show_memcached) {
    $response['memcached_api_version'] = phpversion('memcached');
    if ($is_admin) {
        $m = new Memcached();
        $m->addServer(CMW_MEMCACHED_HOST, CMW_MEMCACHED_PORT);
        $m_data = $m->getStats();
        //$response['memcached'] = [];							// If multiple servers
        foreach ($m_data as $key => $value) {
            //$response['memcached'][$key] = $value['uptime'];	// If multiple servers
            $response['memcached_version'] = $value['version'];
            $response['memcached_uptime'] = time_offset() + $value['uptime'];
        }
        $m->quit();
    }
}
// Command Line Tools //
if (defined('CMW_USING_IMAGEMAGICK') && !$show_specific && $is_admin) {
    unset($out);
    unset($ret);
    exec("convert -version", $out, $ret);
    $response['imagemagick_version'] = $ret ? "ERROR" : preg_split('/\\s+/', $out[0])[2];
 /**
  * @param \Memcached $memcached
  * @throws \Exception
  */
 private function validate(\Memcached $memcached)
 {
     $stats = $memcached->getStats();
     foreach ($this->servers as $server) {
         $host = $server[MemcacheConfigConstants::SERVER_HOST] . ':' . $server[MemcacheConfigConstants::SERVER_PORT];
         if ($stats[$host]['pid'] == -1) {
             throw new \Exception("Error establishing memcache connection to {$host}");
         }
     }
 }
Ejemplo n.º 24
0
<?php

$mc = new Memcached();
$mc->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$mc->addServers(array_map(function ($server) {
    return explode(':', $server, 2);
}, explode(',', $_ENV['MEMCACHEDCLOUD_SERVERS'])));
$mc->setSaslAuthData($_ENV['MEMCACHEDCLOUD_USERNAME'], $_ENV['MEMCACHEDCLOUD_PASSWORD']);
switch ($_GET['a']) {
    case 'set':
        echo $mc->set('welcome_msg', 'Hello from Redis!');
        break;
    case 'get':
        echo $mc->get('welcome_msg');
        break;
    case 'stats':
        foreach ($mc->getStats() as $key => $value) {
            foreach ($value as $k => $v) {
                echo "{$k}: {$v} <br />\n";
            }
        }
        break;
    case 'delete':
        echo $mc->delete('welcome_msg');
        break;
    default:
        echo '';
        break;
}
 /**
  * Get server pool statistics.
  *
  * @link    http://www.php.net/manual/en/memcached.getstats.php
  *
  * @return  array       Array of server statistics, one entry per server.
  */
 public function getStats()
 {
     return $this->m->getStats();
 }
Ejemplo n.º 26
0
 /**
  * Returns a Memcached connection.
  *
  * @param array $options Available options are 'host' and 'port'
  *
  * @return \Memcached
  *
  * @throws RuntimeException
  */
 public function getMemcachedConnection(array $options = [])
 {
     $options = array_replace(['host' => 'localhost', 'port' => 11211], $options);
     if (null !== ($cache = $this->getConnection('memcached', $options))) {
         return $cache;
     }
     if (!extension_loaded('memcached')) {
         throw new RuntimeException('The Memcached cache requires the Memcached extension.');
     }
     $memcached = new \Memcached();
     $memcached->addServer($options['host'], $options['port']);
     $memcached->getStats();
     if (\Memcached::RES_SUCCESS !== $memcached->getResultCode()) {
         throw new RuntimeException(sprintf("Memcached instance with host '%s' and port '%s' is not reachable.", $options['host'], $options['port']));
     }
     return $this->setConnection('memcached', $options, $memcached);
 }
Ejemplo n.º 27
0
if (isset($config['cdp_autocreate'])) {
    $config['dp_autocreate'] = $config['cdp_autocreate'];
}
if (!isset($config['mibdir'])) {
    $config['mibdir'] = $config['install_dir'] . '/mibs';
}
$config['mib_dir'] = $config['mibdir'];
// If we're on SSL, let's properly detect it
if (isset($_SERVER['HTTPS'])) {
    $config['base_url'] = preg_replace('/^http:/', 'https:', $config['base_url']);
}
if ($config['memcached']['enable'] === true) {
    if (class_exists('Memcached')) {
        $memcache = new Memcached();
        $memcache->addServer($config['memcached']['host'], $config['memcached']['port']);
        $memcache->getStats();
    } else {
        echo "WARNING: You have enabled memcached but have not installed the PHP bindings. Disabling memcached support.\n";
        echo "Try 'apt-get install php5-memcached' or 'pecl install memcached'. You will need the php5-dev and libmemcached-dev packages to use pecl.\n\n";
        $config['memcached']['enable'] = 0;
    }
}
// Set some times needed by loads of scripts (it's dynamic, so we do it here!)
$config['time']['now'] = time();
$config['time']['now'] -= $config['time']['now'] % 300;
$config['time']['fourhour'] = $config['time']['now'] - 14400;
// time() - (4 * 60 * 60);
$config['time']['sixhour'] = $config['time']['now'] - 21600;
// time() - (6 * 60 * 60);
$config['time']['twelvehour'] = $config['time']['now'] - 43200;
// time() - (12 * 60 * 60);
 public function getStats()
 {
     return $this->memcached->getStats();
 }
Ejemplo n.º 29
0
 /**
  * returns the current status
  */
 public function getStatus() : array
 {
     return ['status' => parent::getStats(), 'version' => parent::getVersion(), 'server_list' => parent::getServerList()];
 }
Ejemplo n.º 30
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);