本文整理汇总了PHP中Memcached类的典型用法代码示例。如果您正苦于以下问题:PHP Memcached类的具体用法?PHP Memcached怎么用?PHP Memcached使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Memcached类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: validate
public function validate()
{/*{{{*/
$debugger = new Debugger();
$memcacheTime = $msg = '';
foreach ($this->hosts as $memcache)
{
$start = $debugger->getTimeStamp();
$m = new Memcached;
$m->addServer($memcache['host'], $memcache['port']);
$m->set('monitortest', 'haha', 10);
$res = $m->get('monitortest');
$end = $debugger->getTimeStamp();
$diff = $debugger->timeDiff($start, $end);
$key = $memcache['host'].':'.$memcache['port'];
if (false == $res || 'haha' != $res)
{
$msg .= $key.'memcacheʧЧ,';
}
if ($this->maxConnectTime < $diff)
{
$msg .= $key.'Á¬½Ó'.substr($diff, 0, 6).'ms,';
}
$memcacheTime .= "$diff ";
}
error_log(date('Y-m-d H:i:s').' '.rtrim($memcacheTime)."\n", 3, '/tmp/memcache_time.log');
if ($msg)
{
error_log(date('Y-m-d H:i:s').' '.$msg."\n", 3, '/tmp/memcache.log');
}
return $msg;
}/*}}}*/
示例2: getMemcachedInstance
public static function getMemcachedInstance($storageEngineConfig = null)
{
$serverIp = '';
$serverPort = '';
if (!is_null($storageEngineConfig)) {
$serverIp = $storageEngineConfig['ip'];
$serverPort = $storageEngineConfig['port'];
} else {
$registry = \Litpi\Registry::getInstance();
$conf = $registry->get('conf');
$serverIp = $conf['memcached'][0]['ip'];
$serverPort = $conf['memcached'][0]['port'];
}
$output = null;
try {
$memcached = null;
if (class_exists('Memcached', false)) {
$memcached = new \Memcached();
$memcached->addServer($serverIp, $serverPort);
} else {
//Wrapper memcache in Windows
$memcached = new \Litpi\Memcached();
$memcached->addServer($serverIp, $serverPort);
}
$output = $memcached;
} catch (\Exception $e) {
//Can not connect to Memcache Server
echo 'Can not connect to Memcache Server';
}
return $output;
}
示例3: register
public function register(Application $app)
{
$app->setParameter('cache', ['namespace' => null, 'type' => 'array']);
$app->singleton('cache', function () use($app) {
$cache = null;
$type = $app->getParameter('cache.type', 'array');
if ($type == 'array') {
$cache = new ArrayCache();
} elseif ($type == 'apc') {
$cache = new ApcCache();
} elseif ($type == 'xcache') {
$cache = new XcacheCache();
} elseif ($type == 'memcache') {
$cache = new MemcacheCache();
$memcache = new \Memcache();
$memcache->addserver($app->getParameter('cache.memcached.host', '127.0.0.1'), $app->getParameter('cache.memcached.port', 11211));
$cache->setMemcache($memcache);
} elseif ($type == 'memcached') {
$cache = new MemcachedCache();
$memcached = new \Memcached();
$memcached->addServer($app->getParameter('cache.memcached.host', '127.0.0.1'), $app->getParameter('cache.memcached.port', 11211));
$cache->setMemcached($memcached);
}
$cache->setNamespace($app->getParameter('cache.namespace'));
return $cache;
});
}
示例4: handler
public function handler()
{
if (!empty($this->storage)) {
$handler = $this->handler;
} else {
$config = $this->_getConfig()->read();
$handlerName = $config['handler'];
$handlerConfig = isset($config['config']) ? $config['config'] : array();
switch ($handlerName) {
case 'memcache':
if (!isset($handlerConfig['host']) || !isset($handlerConfig['port'])) {
throw new RuntimeException('You must specify memcache host and port in handler config in "' . self::CONFIG_FILE . '"');
}
$memcache = new \Memcache();
$memcache->addServer($handlerConfig['host'], (int) $handlerConfig['port']);
$handler = new MemcacheSessionHandler($memcache);
break;
case 'memcached':
if (!isset($handlerConfig['host']) || !isset($handlerConfig['port'])) {
throw new RuntimeException('You must specify memcache host and port in handler config in "' . self::CONFIG_FILE . '"');
}
$memcached = new \Memcached();
$memcached->addServer($handlerConfig['host'], (int) $handlerConfig['port']);
$handler = new MemcachedSessionHandler($memcached);
break;
case 'native':
default:
$handler = new NativeSessionHandler();
}
}
return $handler;
}
示例5: skipIfMemcacheIsNotRunning
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!');
}
}
开发者ID:lizards-and-pumpkins,项目名称:lib-key-value-store-memcached,代码行数:7,代码来源:MemcachedKeyValueStoreTest.php
示例6: check_login
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 = '';
}
}
示例7: cacheStrategyOnce
/**
* 通过加锁机制在cache失效时并发时只透传一个请求到后端子系统
* @param $method string 方法名
* @param $params array 参数列表
* @param $key string 缓存key
*/
public static function cacheStrategyOnce($method, $params, $key, $expire = 100)
{
// 做法相似,只是需要把概率判断的算法换成使用锁保证高并发请求时严格只有一个请求透传到后端系统
$csfKey = self::getCSTKey($key, 1);
$lockKey = self::getCSTLockKey($key, 1);
$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);
$value = $memcached->get($csfKey);
if (!empty($value) && !empty($value['data']) && !empty($value['doubleExpire'])) {
$doubleExpire = $value['doubleExpire'];
if (time() <= $doubleExpire - $expire) {
// cache还在[start, start + expire]时间内仍有效,无需请求后端
return $value['data'];
}
$isLock = $memcached->get($lockKey);
if (!empty($lockKey)) {
// 有锁,表示当前已有请求到后端去读取最新数据并更新cache;
return $value['data'];
}
}
// cache已过期或者无锁,到后台实时请求并更新cache
$ret = $memcached->set($lockKey, 1, 1);
$data = self::$method($params);
if (isset($data['resultCode']) && $data['resultCode'] == 0) {
unset($data['resultCode']);
$doubleExpire = time() + 2 * $expire;
$value = array('data' => $data, 'doubleExpire' => $doubleExpire);
$ret = $memcached->set($csfKey, $value, $doubleExpire);
}
$ret = $memcached->delete($lockKey, 1);
return $data;
}
示例8: updateJsonInMemcached
/**
* Safe update json in Memcached storage
* @param Memcached $Memcached
* @param string $key
* @param array $array
* @throws Exception
*/
function updateJsonInMemcached(\Memcached $Memcached, $key, array $array)
{
// Create new Lock instance
$Lock = new MemcachedLock($Memcached, 'Lock_' . $key, MemcachedLock::FLAG_CATCH_EXCEPTIONS);
// Acquire lock for 2 sec.
// If lock has acquired in another thread then we will wait 3 second,
// until another thread release the lock. Otherwise it throws a exception.
if (!$Lock->acquire(2, 3)) {
throw new Exception('Can\'t get a Lock');
}
// Get value from storage
$json = $Memcached->get($key);
if (!$json) {
$jsonArray = [];
} else {
$jsonArray = json_decode($json, true);
}
// Some operations with json
$jsonArray = array_merge($jsonArray, $array);
$json = json_encode($jsonArray);
// Update key in storage
$Memcached->set($key, $json);
// Release the lock
// After $lock->release() another waiting thread (Lock) will be able to update json in storage
$Lock->release();
}
示例9: __call
public function __call($method, $args)
{
if ($this->driver === null) {
switch (config()->cache_driver()) {
case 'memcached':
$memcached = new \Memcached();
$memcached->addServer(config()->cache_host(), 11211);
$this->driver = new \Doctrine\Common\Cache\MemcachedCache();
$this->driver->setMemcached($memcached);
break;
case 'apc':
$this->driver = new \Doctrine\Common\Cache\ApcCache();
break;
}
}
switch ($method) {
case 'set':
// $this->driver->delete($args[0]);
$this->driver->save($args[0], json_encode($args[1]));
break;
case 'get':
return json_decode($this->driver->fetch($args[0]));
break;
}
}
示例10: __construct
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;
}
}
示例11: testCheck_RequestRate_MemcachedCollector
public function testCheck_RequestRate_MemcachedCollector()
{
$detector = new Detector();
$status = new \stdClass();
$status->ok = null;
$detector->setKey('someKey')->declareProcessor('requestRate', function (RequestRateProcessor $processor, Detector $detector) {
/* @var $processor \Sokil\FraudDetector\Processor\RequestRateProcessor */
$processor->setCollector($detector->createCollector('memcached', 'requestRate', 5, 1, function ($collector) {
/* @var $collector \Sokil\FraudDetector\Collector\MemcachedCollector */
$memcached = new \Memcached();
$memcached->addServer('127.0.0.1', 11211);
$collector->setMemcached($memcached);
}));
})->onCheckPassed(function () use($status) {
$status->ok = true;
})->onCheckFailed(function () use($status) {
$status->ok = false;
});
for ($i = 0; $i < 5; $i++) {
$detector->check();
$this->assertTrue($status->ok);
}
$detector->check();
$this->assertFalse($status->ok);
usleep(2000000.0);
$detector->check();
$this->assertTrue($status->ok);
}
示例12: getMemcached
/**
* @return \Memcached
*/
protected function getMemcached()
{
$Memcached = new \Memcached();
$Memcached->addServers($this->getTestServers());
$Memcached->flush();
return $Memcached;
}
示例13: init
protected function init()
{
$this->config['host'] = $this->config['host'] ?: 'localhost';
$this->config['port'] = $this->config['port'] ?: 11211;
$this->store = new Memcached();
$this->store->addServer($this->config['host'], $this->config['port'], 100);
}
示例14: process
public function process()
{
$id = $this->get('id');
$state = (string) $this->get('state');
if (!$this->is_moderator()) {
throw new ErrorApi(ErrorApi::INSUFFICIENT_RIGHTS);
}
if (empty($id) || empty($state)) {
throw new ErrorApi(ErrorApi::MISSING_INPUT);
}
$state = Meta::parse($state);
if (empty($state)) {
throw new ErrorApi(ErrorApi::INCORRECT_INPUT);
}
$this->db->update('art', array('sortdate' => $this->db->unix_to_date()), $id);
$this->remove_meta(Meta::ART, $id, Meta::STATE, Meta::STATE_APPROVED);
$this->remove_meta(Meta::ART, $id, Meta::STATE, Meta::STATE_UNAPPROVED);
$this->remove_meta(Meta::ART, $id, Meta::STATE, Meta::STATE_DISAPPROVED);
$this->remove_meta(Meta::ART, $id, Meta::STATE, Meta::STATE_DELETED);
$this->add_meta(Meta::ART, $id, Meta::STATE, $state);
$cache = new \Memcached("access_checker");
$cache->addServer("localhost", 11211);
$cache->delete('is_pic_safe_' . $this->db->get_field('art', 'md5', $id));
$this->set_success(true);
}
示例15: populate
public function populate()
{
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->set('int', 99);
return $m->get('int');
}