Example #1
0
    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;
    }/*}}}*/
 /**
  * @return mixed
  */
 public function get()
 {
     if (isset(static::$cache[$this->key])) {
         return static::$cache[$this->key];
     }
     return $this->memcached->get($this->key);
 }
Example #3
0
 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;
 }
Example #4
0
 /**
  * 解锁
  * @param unknown $key
  */
 public function release($key)
 {
     $key = $this->prefix . $key;
     if ($this->memcached->get($key) === $this->Identifier) {
         $this->memcached->delete($key);
     }
 }
 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;
     });
 }
 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;
 }
 public function testGettingMultipleKeysIsDelegatedToClient()
 {
     $items = ['key1' => 'foo', 'key2' => 'bar'];
     $keys = array_keys($items);
     $this->mockClient->expects($this->once())->method('getMulti')->with($keys)->willReturn($items);
     $this->assertSame($items, $this->store->multiGet(...$keys));
 }
 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!');
     }
 }
Example #9
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 = '';
    }
}
Example #10
0
 /**
  * 通过加锁机制在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;
 }
Example #11
0
/**
 * 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();
}
Example #12
0
 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;
     }
 }
Example #13
0
 public function __destruct()
 {
     if ($this->instance) {
         $this->instance->resetServerList();
         unset($this->instance);
     }
 }
 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;
     }
 }
Example #15
0
 public function flush()
 {
     if (!$this->memcached) {
         throw new CacheException('No memcached defined.');
     }
     $this->memcached->flush();
 }
Example #16
0
 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);
 }
 /**
  * @return \Memcached
  */
 protected function getMemcached()
 {
     $Memcached = new \Memcached();
     $Memcached->addServers($this->getTestServers());
     $Memcached->flush();
     return $Memcached;
 }
Example #18
0
 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);
 }
Example #19
0
 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);
 }
 public function populate()
 {
     $m = new Memcached();
     $m->addServer('localhost', 11211);
     $m->set('int', 99);
     return $m->get('int');
 }
 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);
 }
Example #22
0
 public function getTestLink()
 {
     $cache = new \Memcached();
     $cache->addServer(MEMCACHE_HOST, MEMCACHE_PORT);
     $cache->setOption(Memcached::OPT_COMPRESSION, FALSE);
     return new \r8\Cache\Memcached($cache);
 }
 /**
  * @param $key
  * @return mixed
  */
 public function get($key)
 {
     if (!is_null($this->memcache)) {
         return $this->memcache->get($key);
     }
     return false;
 }
Example #24
0
 protected function setUp()
 {
     $client = new \Memcached();
     $client->addServer('localhost', 11211);
     $client->flush();
     $this->cache = new OffloadCacheMemcached($client);
 }
Example #25
0
 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');
     }
 }
Example #26
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;
 }
Example #27
0
 public function __construct($priority, $address = "127.0.0.1", $port = 11211)
 {
     $memcached = new \Memcached();
     $memcached->addServer($address, $port);
     $this->memcached = $memcached;
     parent::__construct($priority);
 }
Example #28
0
 public static function factory(Configuration $conf)
 {
     switch (strtolower($conf['session-server']['type'])) {
         case 'memcache':
             $memcache = new \Memcache();
             if (!@$memcache->connect($conf['session-server']['host'], $conf['session-server']['port'])) {
                 throw new RuntimeException(sprintf('Unable to connect to memcache server at %s:%s', $conf['session-server']['host'], $conf['session-server']['port']));
             }
             return new MemcacheSessionHandler($memcache);
             break;
         case 'memcached':
             $memcached = new \Memcached();
             if (!@$memcached->addServer($conf['session-server']['host'], $conf['session-server']['port'])) {
                 throw new RuntimeException(sprintf('Unable to connect to memcached server at %s:%s', $conf['session-server']['host'], $conf['session-server']['port']));
             }
             $memcached->getVersion();
             if (\Memcached::RES_SUCCESS !== $memcached->getResultCode()) {
                 throw new RuntimeException(sprintf('Unable to connect to memcached server at %s:%s', $conf['session-server']['host'], $conf['session-server']['port']));
             }
             return new MemcachedSessionHandler($memcached);
             break;
         case 'mongo':
         case 'pdo':
             throw new RuntimeException(sprintf('Session handler %s is not yet supported', $conf['session-server']['type']));
             break;
         default:
             throw new RuntimeException(sprintf('Session handler %s is not a valid type', $conf['session-server']['type']));
             break;
     }
 }
Example #29
0
 public function init($config)
 {
     global $_G;
     if (!$config) {
         if (TAE) {
             $config["host"] = "127.0.0.1";
             $config["port"] = 11211;
         } else {
             $config = $_G['_config']['cache_config'];
         }
     }
     $this->config = $config;
     $connect = new Memcached();
     //声明一个新的memcached链接
     $connect->setOption(Memcached::OPT_COMPRESSION, false);
     //关闭压缩功能
     $connect->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
     //使用binary二进制协议
     $connect->addServer($config['host'], $config['port']);
     //添加OCS实例地址及端口号
     if ($config['username'] && $config['password']) {
         //设置OCS帐号密码进行鉴权,如已开启免密码功能,则无需此步骤
         $connect->setSaslAuthData($config['username'], $config['password']);
     }
     $this->enable = true;
     $this->obj = $connect;
     return $this->enable;
 }
 public static function plugin_activated()
 {
     // When the plug in is activated we flush memcache - as it might hold stale
     // data from a failed HTTP requests (e.g. the admin page)
     $memcache = new \Memcached();
     $memcache->flush();
 }