Create a new Memcached connection instance.

@param array $servers
@param null  $memcache

@return \Memcached|null
@throws \RuntimeException
321456
protected static function connect(array $servers, $memcache = null)
    {
        if (!$memcache) {
            $memcache = new \Memcached();
        }

        foreach ($servers as $server) {
            $memcache->addServer($server['host'], $server['port'], $server['weight']);
        }

        if ($memcache->getVersion() === false) {
            throw new \RuntimeException('could not establish memcached connection!');
        }

        return $memcache;
    }
836972
public function setConnection(\Memcached $memcached)
    {
        $this->connection = $memcached;

        if (!count($this->connection->getServerList())) {
            $this->configureServers();
        }

        $this->setOptions();
        return $this;
    }
135747
protected function connect()
    {
        if (!$this->object) {
            $this->object = new \Memcache;
        }
        foreach ($this->servers as $server) {
            call_user_func_array(array($this->object, 'addServer'), $server);
        }
    }
224985
private function __connect(Memento\Key $key = null)
    {
        if (!is_null($this->groupKey)) {
            $connectKey = $this->groupKey;
        } else {
            $connectKey = $key;
        }

        $config = $this->getServer($connectKey, $this->config);

        $host = null;
        if (isset($config['host'])) {
            $host = $config['host'];
        } elseif (isset($config[0]) && is_string($config[0])) {
            $host = $config[0];
        }

        $port = self::DEFAULT_PORT;
        if (isset($config['port'])) {
            $port = $config['port'];
        } elseif (isset($config[1]) && is_numeric($config[1])) {
            $port = $config[1];
        }

        if (empty($host)) {
            throw new \Exception("Invalid memcache configuration");
        }

        // instantiate to the memcache connection
        $this->memcache = new \Memcache();

        return $this->memcache->connect($host, $port);
    }
1133068
public function connect(array $servers)
	{
		$memcached = $this->getEngine();

		// 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)
		{
			$memcached->addServer(
				$server['host'], $server['port'], $server['weight']
			);
		}

		if ($memcached->getVersion() === false)
		{
			throw new RuntimeException('Could not establish Memcached connection.');
		}

		return $memcached;
	}
224925
protected function addServers($cache, $servers)
    {
        $existingServers = [];
        if ($this->persistentId !== null) {
            foreach ($cache->getServerList() as $s) {
                $existingServers[$s['host'] . ':' . $s['port']] = true;
            }
        }
        foreach ($servers as $server) {
            if (empty($existingServers) || !isset($existingServers[$server->getHost() . ':' . $server->getPort()])) {
                $cache->addServer($server->getHost(), $server->getPort(), $server->getWeight());
            }
        }
    }
244148
public function boot(array $configs = [])
    {
        // find hostname and port address, if they are not exists in configs register default values
        //  default value of hostname is 127.0.0.1
        //  defualt value of port address is 11211
        $host = Arr::get($configs, 'host', '127.0.0.1');
        $port = Arr::get($configs, 'port', 11211);
        $timeout = Arr::get($configs, 'timeout', 30);

        $driver = new Memcache();
        $driver->connect($host, $port, $timeout);

        $this->setDriver($driver);
    }
1357183
public function getMemcached(){
		if(!is_object($this->memcached)){
			if(!class_exists('Memcached')){
				if(DEBUG_MODE){
					BLog::addToLog('Memcached class not found!',LL_ERROR);
					}
				return NULL;
				}
			if(DEBUG_MODE){
				BDebug::message('Memcached]: Connecting to memcached server...');
				}
			$this->memcached=new Memcached();
			$mc=$this->memcached;
			$mc->addServer("127.0.0.1",11211);
			$mc->setOption(Memcached::OPT_BINARY_PROTOCOL,true);
			$this->memcached_ver=$mc->getVersion();
			if(DEBUG_MODE){
				BDebug::message('[Memcached]: ver='.var_export($this->memcached_ver,true));
				}
			}
		return $this->memcached;
		}
351977
protected function createMemcacheDriver()
    {
        $serverArray    = $this->config['servers'];
        $persistent     = boolval($this->config['persistent']);
        $name           = trim($this->config['server_name']);
        $prefix         = trim($this->config['prefix']);
        $expireTime     = intval($this->config['lifetime']);

        if ($persistent && (strlen($name) > 0)) {
            $memcached  = new Memcached($name);
        } else {
            $memcached  = new Memcached();
        }

        if (!sizeof($memcached->getServerList())) {
            $memcached->addServers($serverArray);
        }

        $store = new MemcachedStore($memcached, $prefix);
        return new CacheSessionHandler($store, $expireTime);
    }
1069958
public function memcache_failure($host, $port)
    {
        static $seen = array();

        // only report once
        if (!$seen["$host:$port"]++) {
            $this->mc_available--;
            self::raise_error(array(
                'code' => 604, 'type' => 'db',
                'line' => __LINE__, 'file' => __FILE__,
                'message' => "Memcache failure on host $host:$port"),
                true, false);
        }
    }
183915
protected function setServers(array $servers)
    {
        $this->servers = $servers;
        if (!count($this->servers)) {
            throw new Exception('No servers were given to Memcache', 1213115903);
        }

        $this->memcache = extension_loaded('memcached') ? new \MemCached() : new \Memcache();
        $defaultPort = ini_get('memcache.default_port') ?: 11211;

        foreach ($this->servers as $server) {
            $host = $server;
            $port = 0;

            if (strpos($server, 'tcp://') === 0) {
                $port = $defaultPort;
                $server = substr($server, 6);

                if (strpos($server, ':') !== false) {
                    list($host, $port) = explode(':', $server, 2);
                }
            }

            $this->memcache->addServer($host, $port);
        }
    }
990452
public function write($key, $vars)
    {
        $data   = serialize(array('changed' => time(), 'ip' => $this->ip, 'vars' => $vars));
        $result = $this->memcache->set($key, $data, MEMCACHE_COMPRESSED, $this->lifetime + 60);

        if ($this->debug) {
            $this->debug('set', $key, $data, $result);
        }

        return $result;
    }
901095
final public function initialize()
    {
        $this->_ensureModuleExistence();
        $this->memcache = new Memcache();
        // support multiple hosts using semicolon to separate hosts
        $hosts = explode(";", $this->host);
        // different ports for each hosts the same way
        $ports = explode(";", $this->port);
        if (count($hosts) > 1) {
            if (count($ports) < 1) {
                $ports = array_fill(0, count($hosts), self::DEFAULT_PORT);
            } elseif (count($ports) == 1) {
                // if we have just one port, use it for all hosts
                $_p = $ports[0];
                $ports = array_fill(0, count($hosts), $_p);
            }
            foreach ($hosts as $i => $host) {
                $this->memcache->addServer($host, $ports[$i]);
            }
        } else {
            // just connect to the single host
            $this->memcache->connect($hosts[0], $ports[0]);
        }
    }
152069
def patch_memcache():
    

    def _init(self, servers, *k, **kw):
        self._old_init(servers, *k, **kw)

        nodes = {}
        for server in self.servers:
            conf = {
                'hostname': server.ip,
                'instance': server,
                'port': server.port,
                'weight': server.weight
            }
            nodes[server.ip] = conf
        self.uhashring = HashRing(nodes)

    def _get_server(self, key):
        if isinstance(key, tuple):
            return self._old_get_server(key)

        for i in range(self._SERVER_RETRIES):
            for node in self.uhashring.range(key):
                if node['instance'].connect():
                    return node['instance'], key

        return None, None

    memcache = __import__('memcache')
    memcache.Client._old_get_server = memcache.Client._get_server
    memcache.Client._old_init = memcache.Client.__init__
    memcache.Client.__init__ = _init
    memcache.Client._get_server = _get_server
449442
protected function createRedisClusterInstance(array $servers, array $options)
    {
        return new RedisCluster(
            null,
            array_values($servers),
            $options['timeout'] ?? 0,
            $options['read_timeout'] ?? 0,
            isset($options['persistent']) && $options['persistent']
        );
    }
119434
private function newMemcachedServers(Memcached $memcached, array $servers)
    {
        $serverIndex = [];
        $existingServers = $memcached->getServerList();

        foreach ($existingServers as $server) {
            $serverIndex[$server['host'] . ':' . $server['port']] = true;
        }

        foreach ($servers as $configServer) {
            $server = [
                'host' => array_get($configServer, 'host', ''),
                'port' => array_get($configServer, 'port', 11211),
                'weight' => array_get($configServer, 'weight', 0),
            ];

            if (!isset($serverIndex[$server['host'] . ':' . $server['port']])) {
                yield $server;
            }
        }
    }
1142142
protected function getMemcachedHandler(array $config)
    {
        // Create new memcached instance
        $memcached = $this->app->make(Memcached::class, [
            'CCM_SESSION',
            null,
        ]);

        $servers = array_get($config, 'servers', []);

        // Add missing servers
        foreach ($this->newMemcachedServers($memcached, $servers) as $server) {
            $memcached->addServer(
                array_get($server, 'host'),
                array_get($server, 'port'),
                array_get($server, 'weight')
            );
        }

        // Return a newly built handler
        return $this->app->make(MemcachedSessionHandler::class, [
            $memcached,
            ['prefix' => array_get($config, 'name') ?: 'CCM_SESSION'],
        ]);
    }