萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 操作 Memcached 缓存封装类:MCache 兼容多服务器、压缩、TTL

Memcache vs Memcached 扩展

  • memcache:老旧扩展,不支持一致性哈希、二进制协议、SASL 认证。
  • 推荐 memcached (libmemcached):功能完整、性能更好、原生支持集群。

本文封装基于 Memcache 扩展(兼容旧项目),新项目请改用 Memcached 类。

MCache 类实现

<?php
interface CacheFace {
    public function set($key, $value, $sid = 1, $expire = 0);
    public function get($key, $sid = 1);
    public function remove($key, $sid = 1);
    public function flush();
}

class MCache implements CacheFace {
    private $mem = null;
    private $servers = array();
    private $sid = 1;

    public function __construct($config = array()) {
        if (!class_exists('Memcache')) throw new Exception('Memcache 扩展未安装');
        $this->mem = new Memcache();
        $this->servers = $config ?: array(
            1 => array('host' => '127.0.0.1', 'port' => 11211)
        );
        $this->connect($this->sid);
    }

    private function connect($sid) {
        if (!isset($this->servers[$sid])) throw new Exception("Server $sid not found");
        $s = $this->servers[$sid];
        if (!$this->mem->connect($s['host'], $s['port'])) {
            throw new Exception("Memcache 连接失败: {$s['host']}:{$s['port']}");
        }
        $this->sid = $sid;
    }

    public function set($key, $value, $sid = 1, $expire = 0) {
        $this->connect($sid);
        $flags = MEMCACHE_COMPRESSED; // 自动压缩大值
        $value = is_scalar($value) ? $value : serialize($value);
        // 存在则 replace,不存在则 add(避免竞争用 cas 更好,但旧扩展不支持)
        return $this->mem->replace($key, $value, $flags, $expire)
            ?: $this->mem->add($key, $value, $flags, $expire);
    }

    public function get($key, $sid = 1) {
        $this->connect($sid);
        $val = $this->mem->get($key);
        return $val ? @unserialize($val) : $val;
    }

    public function remove($key, $sid = 1) {
        $this->connect($sid);
        return $this->mem->delete($key);
    }

    public function flush() {
        $this->connect();
        return $this->mem->flush();
    }

    public function __destruct() {
        if ($this->mem) $this->mem->close();
    }
}

使用示例

$cache = new MCache(array(
    1 => array('host'=>'mc1', 'port'=>11211),
    2 => array('host'=>'mc2', 'port'=>11211),
));

$cache->set('hot:article:1', '内容...', 1, 300); // 5分钟
$content = $cache->get('hot:article:1');

迁移到 Memcached 扩展的关键差异

$mc = new Memcached();
$mc->addServers(array(
    array('mc1', 11211, 33), // 权重
    array('mc2', 11211, 67),
));
$mc->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); // 一致性哈希
$mc->set('key', $val, 300); // 自动压缩阈值可配置
copyright © 萬盛學電腦網 all rights reserved