/** * Constructor * * Instantiate the memcache cache object * * @param string $host * @param int $port * @throws Exception * @return \Pop\Cache\Adapter\Memcached */ public function __construct($host = 'localhost', $port = 11211) { if (!class_exists('Memcache')) { throw new Exception('Error: Memcache is not available.'); } $this->memcache = new \Memcache(); if (!$this->memcache->connect($host, (int) $port)) { throw new Exception('Error: Unable to connect to the memcached server.'); } $this->version = $this->memcache->getVersion(); }
public function run($request) { if (!class_exists('Memcache')) { $this->msg("Memcache class does not exist. Make sure that the Memcache extension is installed"); } $host = defined('MEMCACHE_HOST') ? MEMCACHE_HOST : 'localhost'; $port = defined('MEMCACHE_PORT') ? MEMCACHE_PORT : 11211; $memcache = new Memcache(); $connected = $memcache->connect($host, $port); if ($connected) { $this->msg("Server's version: " . $memcache->getVersion()); $result = $memcache->get("key"); if ($result) { $this->msg("Data found in cache"); } else { $this->msg("Data not found in cache"); $tmp_object = new stdClass(); $tmp_object->str_attr = "test"; $tmp_object->int_attr = 123; $tmp_object->time = time(); $tmp_object->date = date('Y-m-d H:i:s'); $tmp_object->arr = array(1, 2, 3); $memcache->set("key", $tmp_object, false, 10); } $this->msg("Store data in the cache (data will expire in 10 seconds)"); $this->msg("Data from the cache:"); echo '<pre>'; var_dump($memcache->get("key")); echo '</pre>'; } else { $this->msg("Failed to connect"); } }
/** * Create a new Memcached connection instance. * * @param array $servers * @return Memcached */ protected static function connect($servers) { $memcache = new \Memcache(); foreach ($servers as $server) { $memcache->addServer($server['host'], $server['port'], true, $server['weight']); } if ($memcache->getVersion() === false) { throw new \Exception('Could not establish memcached connection.'); } return $memcache; }
/** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { // manual connection to Mamcache $memcache = new Memcache(); $memcache->connect("localhost", 11211); echo "Server's version: " . $memcache->getVersion() . "<br />\n"; $data = 'This is working'; $memcache->set("key", $data, false, 10); echo "cache expires in 10 seconds<br />\n"; echo "Data from the cache:<br />\n"; var_dump($memcache->get("key")); echo 'If this is all working, <a href="/welcome/go">click here</a> view comparisions'; }
/** * Create a new Memcache connection. * @param array $servers * @return \Memcache * * @throws \RuntimeException */ public function connect(array $servers) { $memcache = new \Memcache(); // For each server in the array, we'll just extract the configuration and add // the server to the Memcached connection. Once we have added all of these // servers we'll verify the connection is successful and return it back. foreach ($servers as $server) { $memcache->addServer($server['host'], $server['port'], $server['weight']); } if ($memcache->getVersion() === false) { throw new \RuntimeException("Could not establish Memcache connection."); } return $memcache; }
/** * Connect to the configured Memcached servers. * * @param array $servers * @return Memcache */ private static function connect($servers) { if (!class_exists('Memcache')) { throw new \Exception('Attempting to use Memcached, but the Memcached PHP extension is not installed on this server.'); } $memcache = new \Memcache(); foreach ($servers as $server) { $memcache->addServer($server['host'], $server['port'], true, $server['weight']); } if ($memcache->getVersion() === false) { throw new \Exception('Memcached is configured. However, no connections could be made. Please verify your memcached configuration.'); } return $memcache; }
public function test() { $memcache = new Memcache(); $memcache->connect('localhost', 11211) or die("Could not connect"); $version = $memcache->getVersion(); echo "Server's version: " . $version . "\n"; $tmp_object = new stdClass(); $tmp_object->str_attr = 'test'; $tmp_object->int_attr = 123; $memcache->set('key', $tmp_object, false, 10) or die("Failed to save data at the server"); echo "Store data in the cache (data will expire in 10 seconds)\n"; $get_result = $memcache->get('key'); echo "Data from the cache:\n"; var_dump($get_result); }
/** * @param array|\ArrayAccess|MemcacheSource $resource * @throws \General\Cache\Exception\InvalidArgumentException * @return Memcache */ public function setResource($resource) { if ($resource instanceof MemcacheSource) { if (!$resource->getVersion()) { throw new Exception\InvalidArgumentException('Invalid memcache resource'); } $this->resource = $resource; return $this; } if (is_string($resource)) { $resource = array($resource); } if (!is_array($resource) && !$resource instanceof \ArrayAccess) { throw new Exception\InvalidArgumentException(sprintf('%s: expects an string, array, or Traversable argument; received "%s"', __METHOD__, is_object($resource) ? get_class($resource) : gettype($resource))); } $host = $port = $weight = $persistent = null; // array(<host>[, <port>[, <weight>[, <persistent>]]]) if (isset($resource[0])) { $host = (string) $resource[0]; if (isset($resource[1])) { $port = (int) $resource[1]; } if (isset($resource[2])) { $weight = (int) $resource[2]; } if (isset($resource[3])) { $persistent = (bool) $resource[3]; } } elseif (isset($resource['host'])) { $host = (string) $resource['host']; if (isset($resource['port'])) { $port = (int) $resource['port']; } if (isset($resource['weight'])) { $weight = (int) $resource['weight']; } if (isset($resource['persistent'])) { $persistent = (bool) $resource['persistent']; } } if (!$host) { throw new Exception\InvalidArgumentException('Invalid memcache resource, option "host" must be given'); } $this->resource = array('host' => $host, 'port' => $port === null ? self::DEFAULT_PORT : $port, 'weight' => $weight <= 0 ? self::DEFAULT_WEIGHT : $weight, 'persistent' => $persistent === null ? self::DEFAULT_PERSISTENT : $persistent); }
/** * This method MUST be implemented by each driver to setup the `Cache` * instance for each test. * * This method should do the following tasks for each driver test: * * - Test the Cache instance driver is available, skip test otherwise * - Setup the Cache instance * - Call the parent setup method, `parent::setUp()` * * @return void */ public function setUp() { parent::setUp(); if (!extension_loaded('memcache')) { $this->markTestSkipped('Memcache PHP Extension is not available'); } if (!($config = Kohana::$config->load('cache')->memcache)) { $this->markTestSkipped('Unable to load Memcache configuration'); } $memcache = new Memcache(); if (!$memcache->connect($config['servers'][0]['host'], $config['servers'][0]['port'])) { $this->markTestSkipped('Unable to connect to memcache server @ ' . $config['servers'][0]['host'] . ':' . $config['servers'][0]['port']); } if ($memcache->getVersion() === FALSE) { $this->markTestSkipped('Memcache server @ ' . $config['servers'][0]['host'] . ':' . $config['servers'][0]['port'] . ' not responding!'); } unset($memcache); $this->cache(Cache::instance('memcache')); }
/** * This method MUST be implemented by each driver to setup the `Cache` * instance for each test. * * This method should do the following tasks for each driver test: * * - Test the Cache instance driver is available, skip test otherwise * - Setup the Cache instance * - Call the parent setup method, `parent::setUp()` * * @return void */ public function setUp() { parent::setUp(); if (!extension_loaded('memcache')) { $this->markTestSkipped('Memcache PHP Extension is not available'); } if (!($config = Kohana::$config->load('cache.memcache'))) { Kohana::$config->load('cache')->set('memcache', array('driver' => 'memcache', 'default_expire' => 3600, 'compression' => FALSE, 'servers' => array('local' => array('host' => 'localhost', 'port' => 11211, 'persistent' => FALSE, 'weight' => 1, 'timeout' => 1, 'retry_interval' => 15, 'status' => TRUE)), 'instant_death' => TRUE)); $config = Kohana::$config->load('cache.memcache'); } $memcache = new Memcache(); if (!$memcache->connect($config['servers']['local']['host'], $config['servers']['local']['port'])) { $this->markTestSkipped('Unable to connect to memcache server @ ' . $config['servers']['local']['host'] . ':' . $config['servers']['local']['port']); } if ($memcache->getVersion() === FALSE) { $this->markTestSkipped('Memcache server @ ' . $config['servers']['local']['host'] . ':' . $config['servers']['local']['port'] . ' not responding!'); } unset($memcache); $this->cache(Cache::instance('memcache')); }
/** * Returns memcached Version. * * @return string memcached Version */ public function getVersion() { if ($this->isInstalled() === false) { return 'not installed'; } if (extension_loaded('memcache') === false) { return \Webinterface\Helper\Serverstack::printExclamationMark('The PHP Extension "memcache" is required.'); } // hardcoded for now $server = 'localhost'; $port = 11211; $memcache = new \Memcache(); $memcache->addServer($server, $port); $version = @$memcache->getVersion(); $available = (bool) $version; if ($available && @$memcache->connect($server, $port)) { return $version; } else { return \Webinterface\Helper\Serverstack::printExclamationMark('Please wake the Memcache daemon.'); } }
// set default values for command line arguments $cmdargs = ['port' => '161', 'log_level' => LOG__NONE]; // port interfaces to ignore. // // The array key is the hostname. The value is the shortened snmp name. $ignoreports = []; // parse the command line arguments parseArguments(); // create a memcache key: $MCKEY = 'NAGIOS_CHECK_PORT_ERRORS_' . md5($cmdargs['host']); if (!class_exists('Memcache')) { die("ERROR: php5-memcache is required\n"); } $mc = new Memcache(); $mc->connect('localhost', 11211) or die("ERROR: Could not connect to memcache on localhost:11211\n"); _log("Connected to Memcache with version: " . $mc->getVersion(), LOG__DEBUG); require 'OSS_SNMP/OSS_SNMP/SNMP.php'; $snmp = new \OSS_SNMP\SNMP($cmdargs['host'], $cmdargs['community']); // get interface types for later filtering $types = $snmp->useIface()->types(); $names = filterForType($snmp->useIface()->names(), $types, OSS_SNMP\MIBS\Iface::IF_TYPE_ETHERNETCSMACD); _log("Found " . count($names) . " physical ethernet ports", LOG__DEBUG); // get current error counters $ifInErrors = filterForType($snmp->useIface()->inErrors(), $types, OSS_SNMP\MIBS\Iface::IF_TYPE_ETHERNETCSMACD); $ifOutErrors = filterForType($snmp->useIface()->outErrors(), $types, OSS_SNMP\MIBS\Iface::IF_TYPE_ETHERNETCSMACD); _log("Found " . count($ifInErrors) . " entries for in errors on physical ethernet ports", LOG__DEBUG); _log("Found " . count($ifOutErrors) . " entries for out errors on physical ethernet ports", LOG__DEBUG); // delete unwanted entries foreach (array_keys($ignoreports) as $hostkey) { if ($cmdargs['host'] == $hostkey) { $portid = array_keys($names, $ignoreports[$hostkey])[0];
<br /> <hr /> <h2>Extentions</h2> <table border="0" cellpadding="3" width="600"> <tr> <td class="e">APC</td> <td class="v"><?php echo function_exists('apc_sma_info') ? 'Yes' . info('apc_sma_info') : 'No'; ?> </td> </tr> <tr> <td class="e">Memcache</td> <td class="v"><?php echo function_exists('memcache_get_version') ? 'Yes' . $memcache->getVersion() : 'No'; ?> </td> </tr> <tr> <td class="e">GD</td> <td class="v"><?php echo function_exists('gd_info') ? 'Yes' . info('gd_info') : 'No'; ?> </td> </tr> <tr> <td class="e">Imagick</td> <td class="v"><?php echo class_exists('Imagick') ? 'Yes' : 'No'; ?>
<?php header("Content-Type:text/html;charset=utf-8"); //连接 $mem = new Memcache(); $mem->connect("127.0.0.1", 11211) or die("Could not connect"); //显示版本 $version = $mem->getVersion(); echo "Memcached Server version: " . $version . "<br>"; //保存数据 $mem->set('key1', 'This is first value', 0, 60); $val = $mem->get('key1'); echo "Get key1 value: " . $val . "<br>"; //替换数据 $mem->replace('key1', 'This is replace value', 0, 60); $val = $mem->get('key1'); echo "Get key1 value: " . $val . "<br>"; //保存数组 $arr = array('aaa', 'bbb', 'ccc', 'ddd'); $mem->set('key2', $arr, 0, 60); $val2 = $mem->get('key2'); echo "Get key2 value: "; print_r($val2); echo "<br>"; //删除数据 $mem->delete('key1'); $val = $mem->get('key1'); echo "Get key1 value: " . $val . "<br>"; //清除所有数据 $mem->flush(); $val2 = $mem->get('key2');
/** * Create a new Memcache connection instance * * The configuration array passed to this method should be an array of * server hosts/ports, like those defined in the default $configuration * array contained in this class. * * @param array The configuration array * @return Memcache Returns the newly created Memcache instance */ public static function connect($servers = array()) { $memcache = new \Memcache(); foreach ((array) $servers as $server) { $memcache->addServer($server['host'], $server['port'], true, $server['weight']); } if ($memcache->getVersion() === false) { throw new \RuntimeException('Could not establish a connecton to Memcache.'); } return $memcache; }
/** * Устанавливает тестовое соединение с сервером Memcache * @return boolean */ public function testMemcacheConection() { $this->messageSucces = "Настройки корректны, соединение с Memcache установлено успешно."; $this->messageError = "Не удалось установить соединение с сервером Memcache по адресу " . $_POST['host'] . ":" . $_POST['port']; if (class_exists('Memcache')) { $memcacheObj = new Memcache(); $memcacheObj->connect($_POST['host'], $_POST['port']); $this->messageSucces .= " Версия: " . $memcacheObj->getVersion(); $ver = $memcacheObj->getVersion(); if (!empty($ver)) { return true; } $this->messageError = 'Не установлен PHP модуль для работы с Memcache'; return false; } return false; }
} else { _e('XCache Extension is Not Loaded', 'bulletproof-security'); } echo '</strong><br>'; echo __('Varnish', 'bulletproof-security') . ': <strong>'; if (extension_loaded('varnish')) { _e('Varnish Extension is Loaded', 'bulletproof-security'); } else { _e('Varnish Extension is Not Loaded', 'bulletproof-security'); } echo '</strong><br>'; echo __('Memcache', 'bulletproof-security') . ': <strong>'; if (extension_loaded('memcache')) { $memcache = new Memcache(); @$memcache->connect('localhost', 11211); echo __('Memcache Extension is Loaded - ', 'bulletproof-security') . __('Version: ', 'bulletproof-security') . @$memcache->getVersion(); } else { _e('Memcache Extension is Not Loaded', 'bulletproof-security'); } echo '</strong><br>'; echo __('Memcached', 'bulletproof-security') . ': <strong>'; if (extension_loaded('memcached')) { $memcached = new Memcached(); @$memcached->addServer('localhost', 11211); echo __('Memcached Extension is Loaded - ', 'bulletproof-security') . __('Version: ', 'bulletproof-security') . @$memcached->getVersion(); } else { _e('Memcached Extension is Not Loaded', 'bulletproof-security'); } echo '</strong><br>'; echo '</span>'; ?>
<?php //phpinfo(); //require_once 'memcache.php'; $memcache = new Memcache(); $memcache->connect('localhost', 11211) or die("Could not connect"); $version = $memcache->getVersion(); echo "Server's version: " . $version . "<br/>\n"; $tmp_object = new stdClass(); $tmp_object->str_attr = 'test'; $tmp_object->int_attr = 123; $memcache->set('key', $tmp_object, false, 10) or die("Failed to save data at the server"); echo "Store data in the cache (data will expire in 10 seconds)<br/>\n"; $get_result = $memcache->get('key'); echo "Data from the cache:<br/>\n"; var_dump($get_result);
public static function begin() { if (self::$status === true) { return; } $_SERVER['SERVER_ADDR'] = self::getIp(); $project_id = PROJECT_ID; array_shift($_SERVER['argv']); $path = $_SERVER['PWD'] . "/" . $_SERVER['SCRIPT_NAME'] . " " . implode(" ", $_SERVER['argv']); self::$key = md5('project_id:' . $project_id . 'path:' . $path); //mc 50s锁控制 $mc = new Memcache(); $serverArr = explode(" ", self::mcServer); foreach ($serverArr as $v) { if (empty($v)) { continue; } list($server, $port) = explode(":", $v); $mc->addServer($server, $port); } $rs = $mc->add(self::$key, 1, 0, 50); //锁定50s,避免两台服务器时间差导致重复运行 if ($rs === false) { echo date("[Y-m-d H:i:s]") . "get mc lock fail\n"; if ($mc->getVersion() === false) { //MC异常 $url = "http://" . DAGGER_ALARM_URL . "/alarm.php?pid=" . PROJECT_ID . "&key=" . PROJECT_KEY . "&sys_mid=4&code=100&message=" . urlencode("队列MC连接异常,可能影响所有后台任务执行") . "&name=" . urlencode("队列机MC异常"); $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_URL, $url); //$result = curl_exec($ch); echo date("[Y-m-d H:i:s]") . $url . "\n"; curl_close($ch); } exit; } echo date("[Y-m-d H:i:s]") . "get mc lock succ\n"; //数据库锁 self::query("INSERT INTO `queue_runtime` (`project_id`,`task`,`begin_time`,`key`,`ip`) VALUES ('{$project_id}','{$path}','" . time() . "','" . self::$key . "','" . self::getIp() . "')"); $rows = mysql_affected_rows(self::$link); var_dump($rows); if ($rows === 1) { self::query("INSERT INTO `queue_task_log` (`project_id`,`task`,`begin_time`,`ip`) VALUES ('{$project_id}','{$path}','" . time() . "','" . self::getIp() . "')"); self::$logId = mysql_insert_id(self::$link); echo date("[Y-m-d H:i:s]") . "succ run\n"; self::$status = true; return true; } elseif ($rows === false) { //故障时候短信报警,不接入监控大厅,应为出故障的库就是监控大厅的库 $rs = $mc->add(self::$key, 1, 0, 60); if ($rs === true) { // 需要修改 $url = 'http://mix.sina.com.cn/guard/***user=abc&password=abc&phone='; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_URL, $url); //$result = curl_exec($ch); echo date("[Y-m-d H:i:s]") . $url . "\n"; curl_close($ch); } } exit; }
<?php // Multiple servers - stored as host:port, host:port $memcache = new Memcache(); echo "MEMCACHED_SERVERS" . $_SERVER["MEMCACHED_SERVERS"] . "\n"; define('MEMCACHED_SERVERS', $_SERVER['MEMCACHED_SERVERS']); $servers = array(); foreach (explode(',', $_SERVER['MEMCACHED_SERVERS']) as $server) { list($host, $port) = explode(':', $server); $memcache->addServer($host, $port); } echo "Version: " . $memcache->getVersion() . "\n";
$memcache_port = 11211; } $memcache = new Memcache(); foreach ($memcache_servers as $memcache_host) { if ($_GET['debug']) { echo "\n", '$memcache->addServer : ', "{$memcache_host}, {$memcache_port}\n"; } $memcache->addServer($memcache_host, $memcache_port); if ($memcache_save_path) { $memcache_save_path .= ','; } $memcache_save_path .= 'tcp://' . $memcache_host . ':' . $memcache_port; } } } if ($memcache && !$using_MemcachePool) { if (!@$memcache->getVersion()) { if ($_GET['debug']) { echo "\n", '$memcache->getVersion returned false, will not use memcache', "\n"; } $memcache = NULL; } } } else { if ($_GET['debug']) { echo "\nClass 'Memcache' does not exist, can not use memcache\n"; } } if ($_GET['debug']) { echo "\nExitting memcache hook.\n"; }
<?php $memcache = new Memcache(); $memcache->connect("127.0.0.1", 11211); # You might need to set "localhost" to "127.0.0.1" echo "Server's version: " . $memcache->getVersion() . "\n"; $tmp_object = new stdClass(); $tmp_object->str_attr = "test"; $tmp_object->int_attr = 123; $memcache->set("key", $tmp_object, false, 10); echo "Store data in the cache (data will expire in 10 seconds)\n"; echo "Data from the cache:\n"; var_dump($memcache->get("key"));