FastAdmin 缓存 remember 优化

缓存在业务并发上发挥着很重要的作用,但大多数框架的处理都是判断有没有存在,存在那就返回数据,不存在那就获取然后保存数据再返回,可能在不存在会存在很多个请求进行这一步增加了回源到 sql 的压力。为了有效减少这个问题的影响,这边业务对缓存处理做了一些优化,通过 IP 或者指定参数,然后 crontab 定时请求相关接口来持续更新数据,数据缓存的时间大于每次强制更新缓存时间可以做到用户每次都是命中缓存的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use think\Cache;

if(!function_exists('cache_remember')) {
/**
* 如果不存在则写入缓存
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param int $expire 有效时间 0为永久
* @return mixed
*/
function cache_remember($name, $value, $expire = null) {
$force = false;

if(true) {
// 判断访问的 IP
$ip = request()->ip();

if(in_array($ip, [
'127.0.0.1', // 内网IP
])) {
$force = true;
}

// 判断是不是有指定参数
// 强制转 int 如果是有值的字符串结果是 0
if((int) request()->param('force', 0) === 1) {
$force = true;
}
}

// 如果需要强制更新那就直接删除原本数据,不判断数据有没有存在
if($force) {
Cache::rm($name);
}

// 调用 tp 原本处理
return Cache::remember($name, $value, $expire);
}
}
往上