如何在PHP中实现全局进程以定时更新并缓存全局信息?
嘿,作为PHP新手能想到从全局缓存角度优化性能,这点真的很赞!针对你需要全局共享、每分钟更新的信息缓存需求,我给你两个实用的方案,都是实际项目里验证过的:
方案1:内存缓存 + 定时脚本(最推荐)
这是最成熟、维护成本最低的方案,不需要搞复杂的全局进程,靠外部定时任务更新缓存,所有PHP会话直接读共享缓存即可:
- 第一步:选一个全局内存缓存工具,比如
Redis或者Memcached——它们是独立于PHP进程的共享存储,所有PHP会话都能访问到同一批数据。 - 第二步:写一个单独的PHP脚本(比如
update_global_cache.php),实现调用REST API获取数据,然后把数据存入缓存,同时可以设置1分钟的过期时间(或者让定时任务控制更新频率):<?php $apiData = file_get_contents('https://your-rest-api-endpoint'); if ($apiData) { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); // 存入缓存并设置60秒过期 $redis->setex('global_shared_info', 60, $apiData); } ?> - 第三步:用系统定时任务(比如Linux的
cron)每分钟执行这个脚本。打开crontab编辑器(crontab -e),添加一行:* * * * * /usr/bin/php /path/to/your/update_global_cache.php - 第四步:你的业务PHP代码里,直接从缓存读取数据就行,记得加兜底逻辑(避免定时脚本挂了导致无数据):
<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $globalData = $redis->get('global_shared_info'); // 如果缓存没命中,临时调用API获取并写入缓存 if (!$globalData) { $globalData = file_get_contents('https://your-rest-api-endpoint'); $redis->setex('global_shared_info', 60, $globalData); } // 处理数据... $parsedData = json_decode($globalData, true); ?>
方案2:PHP常驻进程(适合有一定基础后尝试)
如果一定要用PHP实现全局常驻进程,可以借助Swoole或Workerman这类扩展来写一个后台进程,专门负责更新数据:
- 写一个常驻进程脚本,用定时器每隔60秒拉取一次API数据,把数据存在内存里,同时可以写入本地共享文件或共享内存,方便业务PHP读取:
<?php use Swoole\Timer; // 全局变量存储数据 $globalSharedData = []; // 初始化获取一次数据 updateGlobalData(); // 设置每分钟更新一次(60000毫秒) Timer::tick(60000, function() { updateGlobalData(); }); // 更新数据的函数 function updateGlobalData() { global $globalSharedData; $apiResponse = file_get_contents('https://your-rest-api-endpoint'); if ($apiResponse) { $globalSharedData = json_decode($apiResponse, true); // 写入本地文件,供业务PHP读取 file_put_contents('/tmp/global_data_cache.json', json_encode($globalSharedData)); } } // 保持进程运行 Swoole\Event::wait(); ?> - 业务PHP代码直接读取这个本地文件即可:
<?php $cacheFile = '/tmp/global_data_cache.json'; if (file_exists($cacheFile)) { $globalData = json_decode(file_get_contents($cacheFile), true); } else { // 兜底逻辑 $globalData = json_decode(file_get_contents('https://your-rest-api-endpoint'), true); } ?> - 注意:这个方案需要你维护常驻进程的运行(比如设置开机自启、进程崩溃自动重启),对新手来说复杂度稍高。
内容的提问来源于stack exchange,提问作者AlexScalar
相关产品推荐
相关产品推荐

