问题由来
在公司项目开发中,原有项目使用yii2框架写的,使用redis存储用户信息,现要使用laravel8开发新的功能模块,需要复用原来的redis用户验证,在laravel中读取时发现了此问题。
以下是我的解决步骤
解决步骤
1、通过排查发现
在yii2中,redis存储的数据格式是json类型,如下图:
在laravel中,redis存储的数据格式是 php serialize (序列化)的数据
2、查看laravel中报错的文件
public function get($key)
{
$value = $this->connection()->get($this->prefix.$key);
return ! is_null($value) ? $this->unserialize($value) : null;
}
通过key获取 $value 打印 发现数据已经出来了,但是又多了一层反序列化,就是这一层反序列化报错了。
思路一转,读取时为什么会加反序列化,除非在添加时有使用序列化。
一般情况下,序列化和反序列化是成对出现的。(重点)
3、马上去查看添加缓存的方法,代码如图:
public function add($key, $value, $seconds)
{
$lua = "return redis.call('exists',KEYS[1])<1 and redis.call('setex',KEYS[1],ARGV[2],ARGV[1])";
return (bool) $this->connection()->eval(
$lua, 1, $this->prefix.$key, $this->serialize($value), (int) max(1, $seconds)
);
}
这时候真相大白了
laravel cache在添加时会将数据序列化,在读取时会将数据反序列化。
解决方案:
把代码中读取缓存的地方:
use Illuminate\Support\Facades\Cache;
Cache::get(key)
改为:
use Illuminate\Support\Facades\Redis;
Redis::get(key)
完美解决,perfect!