解决vue keepAlive第二个入口页面显示的个缓存问题
问题场景: 当某个带有筛选条件查询列表的页面需要进行缓存,以便不再需要重复进行选择或者输入筛选条件的时候,我们就可以利用keepAlive来进行缓存,但keepAlive也存在着一些坑,这是需要注意的
顺晟科技
2021-06-16 10:52:58
147
由于访问令牌有效期只有7200秒,而每天调用获取的次数只有2000次,所以需要将访问令牌进行缓存来保证不触发超过更大调用次数。另外在微信公众平台中,绝大多数接口都需要访问令牌授权才能进行调用,开发者需要使用中控服务器统一进行缓存与更新,以避免各自刷新而混乱。
下面代码使用缓存来保存访问令牌并在3600秒之后自动更新。
复制代码
一类类_weixin
2 {
3 var $ appid=APPID
4 var $ appsecret=APPSECRET
5
6 //构造函数,获取访问令牌
七公共函数_ _构造($appid=NULL,$appsecret=NULL)
8 {
9 if($appid $appsecret){
10 $ this-appid=$ appid;
11 $ this-app secret=$ app secret;
12 }
13
14 //方法1.缓存形式
15 if(isset($ _ SERVER[' HTTP _ APPNAME ']){//SAE环境,需要开通缓存
16 $ mem=memcache _ init();
17 }else { //本地环境,需已安装缓存
18美元mem=新Memcache
19美元mem-connect('localhost ',11211)或' die('无法连接');
20 }
21 $ this-access _ token=$ mem-get($ this-appid);
22 if(!isset($ this-access _ token)| | empty($ this-access _ token)){
23美元网址='https://api.weixin.qq.com/cgi-bin/token?grant _ type=client _ credentialpid=' .$this-appid .秘密=' .$ this-app secret;
24 $ RES=$ this-http _ request($ URL);
25 $result=json_decode($res,true);
26 $ this-access _ token=$ result[' access _ token '];
27 $mem-set($this-appid,$this-access_token,0,3600);
28 }
29
30 //方法2.本地写入
31 $ RES=file _ get _ contents(' access _ token。JSON’);
32 $result=json_decode($res,true);
33 $ this-expires _ time=$ result[' expires _ time '];
34 $ this-access _ token=$ result[' access _ token '];
35
36 if(time()($ this-expires _ time 3600)){
37美元网址='https://api.weixin.qq.com/cgi-bin/token?grant _ type=client _ credentialpid=' .$this-appid .秘密=' .$ this-app secret;
38 $ RES=$ this-http _ request($ URL);
39 $result=json_decode($res,true);
40 $ this-access _ token=$ result[' access _ token '];
41 $ this-expires _ time=time();
42 file _ put _ contents(' access _ token。JSON ',' {'access_token': ' ' .$this-access_token .' expires_time': ' .$this-expires_time .'}');
43 }
44 }
45
46受保护函数http_request($url,$data=null)
47 {
48 $ curl=curl _ init();
49 curl_setopt($curl,CURLOPT_URL,$ URL);
50 curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
51 curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
52 if(!空($data)){
53 curl_setopt($curl,CURLOPT_POST,1);
54 curl_setopt($curl,CURLOPT _ POSTFIELDS,$ data);
55 }
56 curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
57 $ output=curl _ exec($ curl);
58 curl _ close($ curl);
59返回$输出
60 }
61 }
复制代码
上面代码中,定义了一个类class_weixin,在类的构造函数中来更新并缓存访问令牌,该函数介绍使用了两种方法。
方法一:使用缓存缓存的方法,首先对缓存进行初始化(第15行~第22行),然后读取缓存中的访问令牌值(第21行),如果该值不存在或者为空值(第22行),则重新接口获取(第23行~第26行),并将值存在缓存中同时设置过期时间为3600秒(第27行)。
方法二:使用本地文件读写的方式,首先读取文件access_token.json中的值并将文件中的数据格式字符串进行编码转成数组(第31行~第34行),并将文件中access_token和过期时间(_ t)值保存到这对象中,然后判断上次保存的时间距离现在是否已超过3600秒(第36行),如果已经超过则重新调用接口获取(第37行~第41行),并将访问令牌和时间更新到文件access_token.json中(第42行)。
最后,在类中定义了一个受保护的函数http_request。该功能使用curl以get或post的方式向微信公众平台界面请求数据,适用于几乎所有微信界面数据访问和提交。
如果读者在使用方法2时不能自动创建文件或抛出语法错误,他可以在同一目录下创建一个access_token.json文件,并将以下初始内容保存在文件中。
{
access _ token ' : ' abcdefghijklnm ',
过期时间' :1166327133
}
29
2021-08
29
2021-08
16
2021-06
16
2021-06