类设计目标
- 单例管理 Redis 连接池(多服务器分片)
- 统一异常处理、自动序列化、TTL 支持
- 实现通用缓存接口,便于替换后端
完整类代码
<?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 RCache implements CacheFace {
private $redis = null;
private $servers = array();
private $currentSid = 1;
public function __construct($config = array()) {
if (!class_exists('Redis')) throw new Exception('Redis 扩展未安装');
$this->servers = $config ?: array(
1 => array('host' => '127.0.0.1', 'port' => 6379, 'auth' => '', 'db' => 0)
);
$this->redis = new Redis();
$this->connect($this->currentSid);
}
private function connect($sid) {
if (!isset($this->servers[$sid])) throw new Exception("Server $sid not configured");
$s = $this->servers[$sid];
$this->redis->connect($s['host'], $s['port']);
if ($s['auth']) $this->redis->auth($s['auth']);
if ($s['db']) $this->redis->select($s['db']);
$this->currentSid = $sid;
}
public function set($key, $value, $sid = 1, $expire = 0) {
$this->connect($sid);
$value = is_scalar($value) ? $value : serialize($value);
return $expire ? $this->redis->setex($key, $expire, $value)
: $this->redis->set($key, $value);
}
public function get($key, $sid = 1) {
$this->connect($sid);
$val = $this->redis->get($key);
return $val ? @unserialize($val) : $val; // 兼容非序列化值
}
public function remove($key, $sid = 1) {
$this->connect($sid);
return $this->redis->del($key);
}
public function flush() {
$this->connect();
return $this->redis->flushAll();
}
// 进阶:批量操作
public function mGet(array $keys, $sid = 1) {
$this->connect($sid);
return $this->redis->mGet($keys);
}
public function mSet(array $kv, $sid = 1, $expire = 0) {
$this->connect($sid);
$pipe = $this->redis->multi(Redis::PIPELINE);
foreach ($kv as $k => $v) {
$v = is_scalar($v) ? $v : serialize($v);
$pipe->set($k, $v);
if ($expire) $pipe->expire($k, $expire);
}
return $pipe->exec();
}
public function __destruct() {
if ($this->redis) $this->redis->close();
}
}
使用示例
$cache = new RCache(array(
1 => array('host'=>'10.0.0.1', 'port'=>6379, 'auth'=>'secret', 'db'=>0),
2 => array('host'=>'10.0.0.2', 'port'=>6379, 'auth'=>'secret', 'db'=>0),
));
// 存储用户会话
$cache->set('session:u1001', array('name'=>'张三', 'role'=>'admin'), 1, 3600);
// 读取
$user = $cache->get('session:u1001');
// 批量预热商品缓存
$goods = array();
foreach (range(1,100) as $id) $goods["goods:$id"] = array('id'=>$id, 'price'=>rand(10,100));
$cache->mSet($goods, 1, 86400);
生产环境建议
- 使用
predis/predis 或 phpredis 扩展(性能更强)。
- 启用
Redis::SERIALIZER_IGBINARY 或 msgpack 提升序列化效率。
- 集群模式下使用
RedisCluster 客户端,自动槽位路由。
- 监控关键指标:命中率、内存碎片率、慢查询、连接数。