如何在php版本的函数计算中实现超时刷新共享全局变量
一个典型的场景:共享全局变量会在函数实例没有http连接请求或者超过一定时间关闭的时候被释放掉,假设过期时间是10分钟,如果一个全局变量最多2分钟就要让它过期并重新赋值,如何实现呢?
步骤1:设置初始化函数
1.先在函数配置->生命周期函数,点击编辑
在初始化函数中填入main.my_initializer,保存表单

步骤2:在代码根目录下新建main.php
<?php
$xxx = 0;
// 函数计算实例中的数据过期的时间戳
$instance_data_expire_time = time() + 60*2;
// 所有实例启动的时候执行一次
function my_initializer($context){
$dir_path = dirname(__FILE__);
require_once($dir_path.'/lib/online_funcs.php');
//error_log("main.php:requestId={$context['requestId']}");
}
步骤3:在/lib/online_funcs.php中的代码
<?php
// 获取缓存数据过期时间
function get_instance_data_expire_time(){
return $GLOBALS['instance_data_expire_time'];
}
// 设置缓存数据过期时间
function set_instance_data_expire_time($i_time){
$GLOBALS['instance_data_expire_time'] = $i_time;
return true;
}
// 设置全局变量
function set_xxx(){
global $xxx;
error_log("xxx_old = ".$xxx);
$xxx++;
//保存全局变量
$GLOBALS['xxx'] = $xxx;
error_log("xxx_new = ".$xxx);
return $xxx;
}
//获取全局变量
function get_xxx(){
return $GLOBALS['xxx'];
}
步骤4:在入口文件index.php中的入口函数的代码:
<?php
use RingCentral\Psr7\Response;
function handler($request, $context): Response{
$request_body = $request->getBody()->getContents();
$respHeaders = array('Content-Type' => 'application/json');
parse_str($request_body, $arr_post_vars);
//注意这里不需要require_once($dir_path.'/lib/online_funcs.php');这样引入公共函数,因为已经在main.php中引入了
$xxx = get_xxx();
error_log("index.php:xxx = ".$xxx);
error_log("index.php:instance_data_expire_time = ".get_instance_data_expire_time());
if(time() > get_instance_data_expire_time()){
// 设置缓存数据
set_xxx();
// 更新缓存数据过期的时间
set_instance_data_expire_time(time()+ 60 *2);
error_log("index.php:xxx_updated = ".get_xxx());
error_log("index.php:instance_data_expire_time_updated = ".get_instance_data_expire_time());
}
// 下发修改请求间隔
return new Response(200, $respHeaders, json_encode($arr_post_vars , JSON_UNESCAPED_UNICODE));
}
步骤5:发送测试数据
用postman发送10次POST请求,间隔3分钟,查看函数计算的日志:
第1次的日志内容是:

前面几次请求,xxx变量的数值都不会变化,缓存数据的过期时间为2022-02-12 17:27:41
缓存过期后日志内容:

这里我们看见xxx这个全局变量在120秒以后从0被更新成1了,并且缓存数据的过期时间更新为2022-02-12 17:30:03。
详情看阿里云函数计算关于生命周期的描述文档:https://help.aliyun.com/document_detail/203027.html
浙公网安备 33010602011771号