还在为laravel操作缓存而烦恼么,还在思考缓存穿透、缓存击穿、缓存雪崩吗,这个函数将帮助你解决这些问题。
/** * 操作缓存的帮助函数 * * @param $key * @param $ttl * @param callable $getData * @return mixed * @throws \Psr\SimpleCache\InvalidArgumentException */ function cache_store($key, $ttl, callable $get_data) { $dont_cache = false; $data = retry(3, function () use ($key, $ttl, $dont_cache, $getData) { /** @var \Illuminate\Contracts\Cache\Repository $cache */ $cache = app('cache.store'); $data = $cache->get($key); if ($data === false || is_null($data)) { // 可以在此自行加锁,防止穿透 // 如获取到incr=1的去拿数据,其他的都 throw Excepetion 等待 50毫秒后retry,得保证get_data 50毫秒内就能返回 $data = $get_data($dont_cache); // 可以自行动态变化 $ttl 防止雪崩 $dont_cache || $cache->set($key, json_encode($data, JSON_UNESCAPED_UNICODE), $ttl); } else { $data = json_decode($data); } return $data; }, 50); // 50毫秒设置地方 return $data; }
使用方法
// 获取 $data $data = cache_store('some_key', 60, function(&$dont_cache) { $data = $db->query('some sql'); // 如果为空需要跳过缓存(当然了,如果是非法数据的话,会造成击穿) if (empty($data)) { $dont_cache = true; return null; } return $data; }); // 愉快的使用 $data 吧