背景
跨系统读取 redis,如何自定义 key 值?
问题
不同的系统应用,公用 redis 时,由于每个系统配置的 redis 前缀不一样,读取公用 key 时就会读取不到。
(new \think\facade\Cache)->store('redis_remote')->get('wx_token');
举例:A应用默认 redis 前缀为 a_ ,B应用默认前缀为 b_,当 A应用读取 B应用生成的 key(b_wx_token)时,默认读取的是 a_wx_token 。
解决
查看底层实现 \think\cache\driver\Redis::__construct
public function __construct(array $options = [])
{
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
if (extension_loaded('redis')) {
$this->handler = new \Redis;
if ($this->options['persistent']) {
$this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']);
} else {
$this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']);
}
if ('' != $this->options['password']) {
$this->handler->auth($this->options['password']);
}
} elseif (class_exists('\Predis\Client')) {
$params = [];
foreach ($this->options as $key => $val) {
if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
$params[$key] = $val;
unset($this->options[$key]);
}
}
if ('' == $this->options['password']) {
unset($this->options['password']);
}
$this->handler = new \Predis\Client($this->options, $params);
$this->options['prefix'] = '';
} else {
throw new \BadFunctionCallException('not support: redis');
}
if (0 != $this->options['select']) {
$this->handler->select($this->options['select']);
}
}
可以看到初始化后的 $this->handler
是原始的 redis 连接,应用中修改代码如下即可实现自定义key值获取数据:
(new \think\facade\Cache)->store('redis_remote')->handler()->get('b_wx_token');