本文整理汇总了PHP中Memcached类的典型用法代码示例。如果您正苦于以下问题:PHP Memcached类的具体用法?PHP Memcached怎么用?PHP Memcached使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Memcached类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}/*}}}*/
开发者ID:sdgdsffdsfff,项目名称:hdf-client,代码行数:31,代码来源:memcache.php
示例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;
}
开发者ID:tuyenv,项目名称:litpi-framework-3,代码行数:31,代码来源:Cacher.php
示例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;
});
}
开发者ID:itlessons,项目名称:php-application,代码行数:27,代码来源:DoctrineCacheProvider.php
示例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;
}
开发者ID:Rudi9719,项目名称:stein-syn,代码行数:32,代码来源:SessionProvider.class.php
示例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 = '';
}
}
开发者ID:KarlZeo,项目名称:MoyOJ,代码行数:32,代码来源:functions.php
示例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;
}
开发者ID:billfeller,项目名称:frontfunc,代码行数:38,代码来源:cache.php
示例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();
}
开发者ID:cheprasov,项目名称:php-memcached-lock,代码行数:33,代码来源:example.php
示例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;
}
}
开发者ID:moxi9,项目名称:unity,代码行数:25,代码来源:Cache.php
示例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;
}
}
开发者ID:catlabinteractive,项目名称:dolumar-engine,代码行数:35,代码来源:Memcache.php
示例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);
}
开发者ID:sokil,项目名称:php-fraud-detect,代码行数:28,代码来源:DetectorTest.php
示例12: getMemcached
/**
* @return \Memcached
*/
protected function getMemcached()
{
$Memcached = new \Memcached();
$Memcached->addServers($this->getTestServers());
$Memcached->flush();
return $Memcached;
}
开发者ID:cheprasov,项目名称:php-parallel,代码行数:10,代码来源:MemcachedStorageTest.php
示例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);
}
开发者ID:simon-downes,项目名称:spf,代码行数:7,代码来源:Memcache.php
示例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);
}
开发者ID:4otaku,项目名称:api,代码行数:25,代码来源:Approve.php
示例15: populate
public function populate()
{
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->set('int', 99);
return $m->get('int');
}
开发者ID:chetantarale,项目名称:sample_php_memcached,代码行数:7,代码来源:MemcachedExample.php
示例16: defaultAction
public function defaultAction()
{
// Line chart
$memcache = new \Memcached();
$stats1 = $memcache->get('stats1');
if ($stats1 === false) {
$stats = Stat::select(DB::raw('max(`packages`) as packages'), DB::raw('sum(`added`) as added'), DB::raw('date(`created_at`) as date'))->orderBy('date', 'asc')->groupBy('date')->get();
$stats1 = [['Date', 'Total', 'New']];
foreach ($stats as $stat) {
$stats1[] = [$stat->date, (int) $stat->packages, (int) $stat->added];
}
$memcache->set('stats1', $stats1, self::DAY);
}
// Domain table
$memcache = new \Memcached();
$stats2 = $memcache->get('stats2');
if ($stats2 === false) {
$stats2 = Package::select(['domain', DB::raw('count(domain) as count')])->groupBy('domain')->where('domain', '<>', '')->orderBy('count', 'desc')->get()->toArray();
$memcache->set('stats2', $stats2, self::DAY);
}
// Types table
$memcache = new \Memcached();
$stats3 = $memcache->get('stats3');
if ($stats3 === false || true) {
$stats3 = Package::select(['type', DB::raw('count(type) as count')])->groupBy('type')->where('type', '<>', '')->having('count', '>', 9)->orderBy('count', 'desc')->get()->toArray();
$memcache->set('stats3', $stats3, self::DAY);
}
$this->_setTitle('Stats');
return new StatsView($stats1, $stats2, $stats3);
}
开发者ID:Jleagle,项目名称:php-packages.com,代码行数:30,代码来源:StatsController.php
示例17: getTestLink
public function getTestLink()
{
$cache = new \Memcached();
$cache->addServer(MEMCACHE_HOST, MEMCACHE_PORT);
$cache->setOption(Memcached::OPT_COMPRESSION, FALSE);
return new \r8\Cache\Memcached($cache);
}
开发者ID:Nycto,项目名称:Round-Eights,代码行数:7,代码来源:Memcached.php
示例18: setUp
protected function setUp()
{
$client = new \Memcached();
$client->addServer('localhost', 11211);
$client->flush();
$this->cache = new OffloadCacheMemcached($client);
}
开发者ID:aol,项目名称:offload,代码行数:7,代码来源:OffloadCacheMemcachedTest.php
示例19: init
public function init()
{
parent::init();
if (!$this->isComponentActive()) {
return;
}
try {
$this->userInfo = call_user_func($this->userInfoCallable);
$this->setUser($this->userInfo);
$memcacheServerName = $this->cacheServer['host'];
$memcacheServerPort = $this->cacheServer['port'];
if ($memcacheServerName && $memcacheServerPort) {
$memcached = new \Memcached();
$memcached->addServer($memcacheServerName, $memcacheServerPort);
$cacheDriver = new \Doctrine\Common\Cache\MemcachedCache();
$cacheDriver->setMemcached($memcached);
$cacheStorage = new \Kevinrob\GuzzleCache\Storage\DoctrineCacheStorage($cacheDriver);
} else {
$cacheStorage = new \Kevinrob\GuzzleCache\Storage\DoctrineCacheStorage(new \Doctrine\Common\Cache\FilesystemCache('/tmp/'));
}
$this->client = new \LaunchDarkly\LDClient($this->apiKey, array("cache" => $cacheStorage));
$this->featureToggleUser = (new \LaunchDarkly\LDUserBuilder($this->user->key))->secondary($this->user->secondary)->ip($this->user->ip)->country($this->user->country)->email($this->user->email)->name($this->user->name)->avatar($this->user->avatar)->firstName($this->user->firstName)->lastName($this->user->lastName)->anonymous($this->user->anonymous)->custom(array('type' => $this->user->type, 'parentCompanyId' => $this->user->parentId, 'referredAccountId' => $this->user->referredAccountId, 'channel' => $this->user->channel, 'payoutMethod' => isset($this->user->payoutMethod) ? $this->user->payoutMethod : null))->build();
} catch (\Exception $ex) {
$this->componentActive = false;
\Yii::log("Cannot initiate Feature Toggles: {$ex->getMessage()}", \CLogger::LEVEL_WARNING, 'system.featureToggle');
}
}
开发者ID:BehalfFE,项目名称:featureToggle,代码行数:27,代码来源:FeatureToggle.php
示例20: __construct
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;
}
开发者ID:StudsPro,项目名称:island-peeps-2.0,代码行数:34,代码来源:Cache.php
注:本文中的Memcached类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论