Contributed by
Rob Frawley and Nicolas Grekas
in #20858 and #21108.

Symfony的Cache组件包含了几种adapters(适配器),以支持不同的缓存架构,诸如Redis,APCuA,文件系统等。在Symfony 3.3中,我们添加了一个全新的Memcached适配器

当作为组件使用时,创建连接到Memcached服务器的第一个连接,然后把这个新的adapter实例化:

1
2
3
4
use Symfony\Component\Cache\Adapter\MemcachedAdapter;
 
$client = MemcachedAdapter::createConnection('memcached://localhost');
$cache = new MemcachedAdapter(\Memcached $client, $namespace = '', $defaultLifetime = 0);

除了连向简单的服务器,连接还可以一个Memcached实例的簇(cluster),可带有全部自定义配置:

1
2
3
4
5
6
7
8
9
10
$client = MemcachedAdapter::createConnection(array(
    // format => memcached://[user:pass@][ip|host|socket[:port]][?weight=int]
    // 'weight' ranges from 0 to 100 and it's used to prioritize servers
    // 'weight' 的范围是从 0 到 100,用于支持优先级的服务器
    'memcached://my.server.com:11211'
    'memcached://rmf:abcdef@localhost'
    'memcached://127.0.0.1?weight=50'
    'memcached://username:the-password@/var/run/memcached.sock'
    'memcached:///var/run/memcached.sock?weight=20'
));

当用在Symfony框架中时,配置和使用Memcached就更加简单了:

1
2
3
4
5
6
7
8
9
10
11
# app/config/config_prod.yml
framework:
    cache:
        # defaults to memcached://localhost / 默认是memcached://localhost
        default_memcached_provider: "memcached://my.server.com:11211"
        # ...
        pools:
            app.cache.products:
                adapter: cache.adapter.memcached
                public: true
                # ...

现在你可以在基于Memcached的缓存中存储和取出元素了:

1
2
3
4
5
6
7
8
$cacheProduct = $this->get('app.cache.products')->getItem($productId);
if (!$cacheProduct->isHit()) {
    $product = ...
    $cacheProduct->set($product);
    $this->get('app.cache.products')->save($cacheProduct);
} else {
    $product = $cacheProduct->get();
}