配置多个服务器,在 Illuminate\Cache\MemcachedConnector
使用addServer
添加进 memcached 具体见文档
cat config/cache.php
'memcached' => [
'driver' => 'memcached',
'servers' =>
[
[
'host' => '127.0.0.1', 'port' => 11211, 'weight' => 80
],
[
'host' => '127.0.0.1', 'port' => 11212, 'weight' => 20
],
],
https://laravel-china.org/top...
public function connect(array $servers)
{
$memcached = $this->getMemcached();
// 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']
);
}
$memcachedStatus = $memcached->getVersion();
//Where a connection has failed to a server the version is returned as '255.255.255'.
array:2 [▼
"xxx:11211" => "1.5.5"
"xxx:11222" => "1.5.5"
]
if (! is_array($memcachedStatus)) {
throw new RuntimeException('No Memcached servers added.');
}
if (in_array('255.255.255', $memcachedStatus) && count(array_unique($memcachedStatus)) === 1) {
throw new RuntimeException('Could not establish Memcached connection.');
}
return $memcached;
}
cat Illuminate\Cache\Repository.php
public function get($key, $default = null)
{
//$this->store 来自Illuminate\Cache\MemcachedStore
dump($this->store->getmemcached()->getstats());//返回config/cache.php memcached servers数组服务器信息
$value = $this->store->get($key);
if (is_null($value))
{
$this->fireCacheEvent('missed', [$key]);
$value = value($default);
}
else
{
$this->fireCacheEvent('hit', [$key, $value]);
}
return $value;
}
cat bootstarp/app.php
$app['events']->listen('cache.write',function($key, $value, $time) use ($app){
dump(app('cache')->store(),app('cache.store')->getStore()->getMemcached()->getstats());
});
测试
echo \Cache::get('test');
// 调用函数里 $this->store->getmemcached()->getstats() 输出的还是2个服务器信息 ["127.0.0.1:11221" => [],"127.0.0.1:11222" => [],]
,怎么知道获取 test 缓存的时候具体连接的哪个服务器呢?
laravel使用的memcached客户端是 php-memcached 该客户端是C实现,底层封装了 libmemcached 。
我们可以直接看下 C 源码是怎么获取一个服务器上的值的,经查找,在文件
libmemcached/get.c
中get源码实现如下:如果你调用的方法没有指定服务器,会通过
memcached_generate_hash_with_redistribution
方法计算key的hash值,然后调用memcached_server_instance_fetch
方法获取memcached实例,并执行命令。而如果使用的是set方法,源文件
libmemcached/storage.c
中实现如下:通过以上的源码发现,参数
weight
方法貌似没用。源码中该方法也仅仅是赋值给了 memcached 的实例,源文件libmemcached/server.c
中的实现:并没有找到具体在哪使用的,计算hash的方法注释掉的有一段如下:
貌似有用到
weight
的值,但是但是源码确实加了#if 0
的判断。