예제 #1
0
파일: Cache.php 프로젝트: ultractiv/lean
 protected function __construct()
 {
     if (class_exists('\\Memcached')) {
         $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);
         // 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]);
             }
         }
         // setup authentication
         if (defined('MEMCACHE_USERNAME') && defined('MEMCACHE_PASSWORD')) {
             $m->setSaslAuthData(MEMCACHE_USERNAME, MEMCACHE_PASSWORD);
         }
         $this->memcache = $m;
     }
 }
예제 #2
0
 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;
     }
 }
예제 #3
0
 /**
  * Initialize the Cache Engine
  *
  * Called automatically by the cache frontend
  *
  * @param array $config array of setting for the engine
  * @return bool True if the engine has been successfully initialized, false if not
  * @throws \InvalidArgumentException When you try use authentication without
  *   Memcached compiled with SASL support
  */
 public function init(array $config = [])
 {
     if (!extension_loaded('memcached')) {
         return false;
     }
     $this->_serializers = ['igbinary' => Memcached::SERIALIZER_IGBINARY, 'json' => Memcached::SERIALIZER_JSON, 'php' => Memcached::SERIALIZER_PHP];
     if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) {
         $this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK;
     }
     parent::init($config);
     if (!empty($config['host'])) {
         if (empty($config['port'])) {
             $config['servers'] = [$config['host']];
         } else {
             $config['servers'] = [sprintf('%s:%d', $config['host'], $config['port'])];
         }
     }
     if (isset($config['servers'])) {
         $this->config('servers', $config['servers'], false);
     }
     if (!is_array($this->_config['servers'])) {
         $this->_config['servers'] = [$this->_config['servers']];
     }
     if (isset($this->_Memcached)) {
         return true;
     }
     if ($this->_config['persistent']) {
         $this->_Memcached = new Memcached((string) $this->_config['persistent']);
     } else {
         $this->_Memcached = new Memcached();
     }
     $this->_setOptions();
     if (count($this->_Memcached->getServerList())) {
         return true;
     }
     $servers = [];
     foreach ($this->_config['servers'] as $server) {
         $servers[] = $this->_parseServerString($server);
     }
     if (!$this->_Memcached->addServers($servers)) {
         return false;
     }
     if (is_array($this->_config['options'])) {
         foreach ($this->_config['options'] as $opt => $value) {
             $this->_Memcached->setOption($opt, $value);
         }
     }
     if (empty($this->_config['username']) && !empty($this->_config['login'])) {
         throw new InvalidArgumentException('Please pass "username" instead of "login" for connecting to Memcached');
     }
     if ($this->_config['username'] !== null && $this->_config['password'] !== null) {
         $sasl = method_exists($this->_Memcached, 'setSaslAuthData') && ini_get('memcached.use_sasl');
         if (!$sasl) {
             throw new InvalidArgumentException('Memcached extension is not build with SASL support');
         }
         $this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
         $this->_Memcached->setSaslAuthData($this->_config['username'], $this->_config['password']);
     }
     return true;
 }
예제 #4
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;
 }
예제 #5
0
 /**
  * @return \Memcached
  * @throws InvalidConfigException
  */
 public function getMemcached()
 {
     if (null === $this->instance) {
         if (!extension_loaded('memcached')) {
             throw new InvalidConfigException(__CLASS__ . ' requires PHP `memcached` extension to be loaded.');
         }
         $this->instance = new \Memcached($this->persistentId);
         // SASL authentication
         // @see http://php.net/manual/en/memcached.setsaslauthdata.php
         if (ini_get('memcached.use_sasl') && (null !== $this->username || null !== $this->password)) {
             if (method_exists($this->instance, 'setSaslAuthData')) {
                 $this->instance->setSaslAuthData($this->username, $this->password);
             }
         }
         if (!empty($this->options)) {
             $this->instance->setOptions($this->options);
         }
     }
     return $this->instance;
 }
예제 #6
0
 private function connect($configServerArray)
 {
     $obj = new Memcached();
     $obj->addServer($configServerArray['host'], $configServerArray['port'], $configServerArray['height']);
     if (!empty($configServerArray['auth'])) {
         $obj->setOption(Memcached::OPT_COMPRESSION, false);
         //关闭压缩功能
         $obj->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
         //使用binary二进制协议
         $auth = $configServerArray['auth'];
         $obj->setSaslAuthData($auth['user'], $auth['password']);
         //设置OCS帐号密码进行鉴权,如已开启免密码功能,则无需此步骤
     }
     return $obj;
 }
예제 #7
0
 /**
  * @return \Memcached
  * @throws \Exception
  */
 public function getCache()
 {
     if ($this->cache == null) {
         if (!extension_loaded('memcached')) {
             throw new \Exception('Requires PHP memcached extension to be loaded');
         }
         $this->cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached();
         if ($this->username !== null || $this->password !== null) {
             $this->cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
             $this->cache->setSaslAuthData($this->username, $this->password);
         }
         if (!empty($this->options)) {
             $this->cache->setOptions($this->options);
         }
     }
     return $this->cache;
 }
예제 #8
0
 public function __construct($arrConfig = array())
 {
     $mark = isset($arrConfig['mark']) ? $arrConfig['mark'] : serialize($arrConfig);
     //标记mem服务,避免重复连接
     $mem = new \Memcached($mark);
     if (isset($arrConfig['auth']) && isset($arrConfig['password'])) {
         //需要认证的mem服务
         if (count($mem->getServerList()) == 0) {
             $mem->setOption(\Memcached::OPT_COMPRESSION, false);
             $mem->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
             $mem->addServer($arrConfig['host'], $arrConfig['port']);
             $mem->setSaslAuthData($arrConfig['auth'], $arrConfig['password']);
         }
     } else {
         $mem->addServer($arrConfig['host'], $arrConfig['port']);
         //不需要认证的mem服务
     }
     $this->mem = $mem;
 }
예제 #9
0
 public static function connectCache($instance, $isMater = true)
 {
     if (!empty($_SERVER['isdaemon'])) {
         //$isMater = true;
     }
     if (!self::$CACHE_ENABLE) {
         return false;
     }
     if (isset(self::$connectpool[$instance]) && @$_SERVER['isdaemon'] == 0) {
         //return self::$connectpool[$instance];
     }
     $isMater = true;
     try {
         if ($isMater) {
             $conf = $_SERVER['cache_conf'][$instance]['master'];
             $connect = new Memcached();
             $connect->setOption(Memcached::OPT_COMPRESSION, false);
             $connect->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
             $connect->addServer($conf['host'], $conf['port']);
             if (!in_array($instance, array('userinfo', 'userhonor', 'userdigg', 'userhomecover', 'userdiggcount', 'userlbsinfo', 'passport'))) {
                 $connect->setSaslAuthData($conf['user'], $conf['passwd']);
             }
         } else {
             $conf = $_SERVER['cache_conf'][$instance]['slave'];
             $connect = new Memcached($instance);
             if (count($connect->getServerList()) == 0) {
                 $connect->setOption(Memcached::OPT_COMPRESSION, false);
                 $connect->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
                 $connect->addServer($conf['host'], $conf['port']);
                 if (!in_array($instance, array('userinfo', 'userhonor', 'userdigg', 'userhomecover', 'userdiggcount', 'userlbsinfo', 'passport'))) {
                     $connect->setSaslAuthData($conf['user'], $conf['passwd']);
                 }
             }
         }
         self::$connectpool[$instance] = $connect;
         return $connect;
     } catch (Exception $e) {
         // log $e->getMessage();
         return false;
     }
 }
예제 #10
0
    $servers[$i] = explode(":", $servers[$i]);
}
// Using Memcached client (recommended)
// ------------------------------------
$m = new Memcached("memcached_pool");
$m->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE);
// Enable no-block for some performance gains but less certainty that data has
// been stored.
$m->setOption(Memcached::OPT_NO_BLOCK, TRUE);
// Failover automatically when host fails.
$m->setOption(Memcached::OPT_AUTO_EJECT_HOSTS, TRUE);
// Adjust timeouts.
$m->setOption(Memcached::OPT_CONNECT_TIMEOUT, 2000);
$m->setOption(Memcached::OPT_POLL_TIMEOUT, 2000);
$m->setOption(Memcached::OPT_RETRY_TIMEOUT, 2);
$m->setSaslAuthData(getenv("MEMCACHIER_USERNAME"), getenv("MEMCACHIER_PASSWORD"));
if (!$m->getServerList()) {
    // 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.
    $m->addServers($servers);
}
// Enable MemCachier session support
session_start();
$_SESSION['test'] = 42;
// Using MemcacheSASL client
// -------------------------
// $m->setSaslAuthData(getenv("MEMCACHIER_USERNAME"), getenv("MEMCACHIER_PASSWORD"));
// $m = new MemcacheSASL();
// if (!$m->getServerList()) {
//   $m->addServers($servers);
 public function initModules()
 {
     $this->register(new ConsoleServiceProvider(), array('console.name' => 'AnyContent CMCK Console', 'console.version' => '1.0.0', 'console.project_directory' => APPLICATION_PATH));
     foreach ($this->modules as $module) {
         $class = $module['class'] . '\\Module';
         $o = new $class();
         $o->init($this, $module['options']);
         $module['module'] = $o;
         $this->modules[$module['class']] = $module;
     }
     $this->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => array_reverse($this->templatesFolder)));
     $this['twig']->setCache(APPLICATION_PATH . '/twig-cache');
     // Init Cache
     $cacheConfiguration = $this['config']->getCacheConfiguration();
     switch ($cacheConfiguration['driver']['type']) {
         case 'none':
             $cacheDriver = new ArrayCache();
             break;
         case 'apc':
             $cacheDriver = new \Doctrine\Common\Cache\ApcCache();
             $this->setCacheDriver($cacheDriver);
             break;
         case 'memcached':
             $memcached = new \Memcached();
             $memcached->addServer($cacheConfiguration['driver']['host'], $cacheConfiguration['driver']['port']);
             $memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, 1);
             if (array_key_exists('username', $cacheConfiguration['driver'])) {
                 $memcached->setSaslAuthData($cacheConfiguration['driver']['username'], $cacheConfiguration['driver']['password']);
             }
             $cacheDriver = new \Doctrine\Common\Cache\MemcachedCache();
             $cacheDriver->setMemcached($memcached);
             $this->setCacheDriver($cacheDriver);
             break;
         case 'file':
             $cacheDriver = new PhPFileCache(APPLICATION_PATH . '/doctrine-cache', 'txt');
             $this->setCacheDriver($cacheDriver);
             break;
         case 'mysql':
             $cacheDriver = new MySQLCache($cacheConfiguration['driver']['host'], $cacheConfiguration['driver']['dbname'], $cacheConfiguration['driver']['tablename'], $cacheConfiguration['driver']['user'], $cacheConfiguration['driver']['password'], $cacheConfiguration['driver']['port']);
             $this->setCacheDriver($cacheDriver);
             break;
         default:
             throw new \Exception('Unknown authentication adapter type ' . $cacheConfiguration['driver']['type'] . '.');
             break;
     }
     $client = $this->getClient();
     $client->setCacheProvider($cacheDriver);
     // Now add the repositories
     $this->getRepositoryManager()->init();
     // Then run all modules
     foreach ($this->modules as $module) {
         $module['module']->run($this);
     }
     $this['repos']->setUserInfo($this['user']->getClientUserInfo());
 }
예제 #12
0
 /**
  * Conexion::memcached()
  * 
  * Genera el proceso de conexion a servidor memcached
  * 
  * @param object $confg
  * @return void
  */
 private function memcached()
 {
     $parametros = ConfigCache::leer('driver', 'memcached');
     $OPT_BINARY_PROTOCOL = (is_bool($parametros['usuario']) == false and is_bool($parametros['clave']) == false) ? (bool) true : (bool) false;
     $memcached = new \Memcached();
     $memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, $OPT_BINARY_PROTOCOL);
     $memcached->addServer($parametros['servidor'], $parametros['puerto']);
     if (is_bool($parametros['usuario']) == false and is_bool($parametros['clave']) == false) {
         $memcached->setSaslAuthData($parametros['usuario'], $parametros['clave']);
     }
     $cacheDriver = new \Doctrine\Common\Cache\MemcachedCache();
     $cacheDriver->setMemcached($memcached);
     return $cacheDriver;
 }
 /**
  * Set the SASL credentials on the Memcached connection.
  *
  * @param  \Memcached  $memcached
  * @param  array  $credentials
  * @return void
  */
 protected function setCredentials($memcached, $credentials)
 {
     list($username, $password) = $credentials;
     $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
     $memcached->setSaslAuthData($username, $password);
 }
예제 #14
0
<?php

header("Content-Type: text/plain");
$mc = new Memcached();
$url = $_GET['u'];
$refresh = (int) $_GET['refresh'];
if ($mc) {
    $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']);
    if ($url == "https://go.berniesanders.com/page/event/search_results?format=json&wrap=no&orderby[0]=date&orderby[1]=desc&event_type=13&mime=text/json&limit=4000&country=*" || $url == "https://docs.google.com/spreadsheets/d/1IaJQtbrsb8_bxpoayN-DhgAb3o_RMUDZyI4TwADmM1g/export?gid=0&format=csv") {
        if ($refresh) {
            $content = file_get_contents($url);
            $mc->set($url, $content);
            echo "-- Refresh {$url} --";
        } else {
            if ($mc->get($url)) {
                $content = $mc->get($url);
            } else {
                $content = file_get_contents($url);
                $mc->set($url, $content);
            }
            echo $content;
        }
    }
} else {
    return;
}
//  $data = json_decode($content);
예제 #15
0
<?php

/**
 * Created by PhpStorm.
 * User: shaoting
 * Date: 15/7/25
 * Time: 下午2:49
 */
//
//
$connect = new Memcached();
//声明一个新的memcached链接
$connect->setOption(Memcached::OPT_COMPRESSION, false);
//关闭压缩功能
$connect->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
//使用binary二进制协议
$connect->addServer('7e3d812f3aa14d09.m.cnhzaliqshpub001.ocs.aliyuncs.com', 11211);
//添加OCS实例地址及端口号
$connect->setSaslAuthData('7e3d812f3aa14d09', 'Aliyun6161361');
//设置OCS帐号密码进行鉴权,如已开启免密码功能,则无需此步骤
echo "dsf" . $connect->get(11223);
$connect->close();
예제 #16
0
 /**
  * 获取memcached实例
  * @param string $server
  * @return Memcached
  */
 private function getMemcached($server = '')
 {
     //实现单例
     static $memc;
     if (!$memc instanceof Memcached) {
         $memc = new Memcached('ocs');
         //声明一个新的memcached链接,这里的ocs就是persistent_id
         if (count($memc->getServerList()) == 0) {
             //echo "New connection"."";
             /*所有option都要放在判断里面,因为有的option会导致重连,让长连接变短连接!*/
             $memc->setOption(Memcached::OPT_COMPRESSION, false);
             $memc->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
             /* addServer 代码必须在判断里面,否则相当于重复建立’ocs’这个连接池,可能会导致客户端php程序异常*/
             $memc->addServer('', 11211);
             //添加OCS实例地址及端口号
             $memc->setSaslAuthData('', '');
             //设置OCS帐号密码进行鉴权,如已开启免密码功能,则无需此步骤
         } else {
             //echo "Now connections is:".count($memc->getServerList())."";
         }
     }
     return $memc;
 }
예제 #17
0
 /**
  * Memcached::inputConfiguracion()
  * 
  * Genera el objeto de manejo de cache
  * 
  * @return object
  */
 private function inputConfiguracion()
 {
     $confg = ConfigCache::leer('driver', 'memcached');
     $this->duracion = $confg['expiracion'];
     $this->servidor = $confg['nombreServidor'];
     $OPT_BINARY_PROTOCOL = (is_bool($confg['usuario']) == false and is_bool($confg['clave']) == false) ? (bool) true : (bool) false;
     $memcached = new \Memcached($this->app);
     $memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, $OPT_BINARY_PROTOCOL);
     $memcached->addServer($confg['servidor'], $confg['puerto']);
     if (is_bool($confg['usuario']) == false and is_bool($confg['clave']) == false) {
         $memcached->setSaslAuthData($confg['usuario'], $confg['clave']);
     }
     return $memcached;
 }