php 实现心跳
PHP 实现心跳机制的方法
心跳机制通常用于检测连接或服务的存活状态。在PHP中可以通过以下方式实现:
定时请求保持连接
使用file_get_contents或cURL定期访问目标URL:
$url = 'http://example.com/heartbeat';
$interval = 30; // 秒
while (true) {
file_get_contents($url);
sleep($interval);
}
使用WebSocket长连接
通过Ratchet等库实现WebSocket心跳:
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Heartbeat implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {
// 新连接
}
public function onMessage(ConnectionInterface $conn, $msg) {
// 处理心跳消息
if ($msg === 'PING') {
$conn->send('PONG');
}
}
// ...其他必要方法
}
数据库定时更新
用数据库记录最后活跃时间:
// 更新心跳时间
function updateHeartbeat($userId) {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare("UPDATE users SET last_heartbeat = NOW() WHERE id = ?");
$stmt->execute([$userId]);
}
// 检查超时
function checkTimeout($userId, $timeout = 300) {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare("SELECT last_heartbeat FROM users WHERE id = ?");
$stmt->execute([$userId]);
$last = $stmt->fetchColumn();
return strtotime($last) > (time() - $timeout);
}
使用Redis过期键
利用Redis的键过期特性:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 更新心跳
$redis->setex("user:{$userId}:heartbeat", 60, 'alive');
// 检查状态
$alive = $redis->exists("user:{$userId}:heartbeat");
定时任务(Cron Job)
通过系统定时任务触发PHP脚本:
* * * * * /usr/bin/php /path/to/heartbeat.php
注意事项
- 长时间运行的PHP脚本需要设置
set_time_limit(0) - 考虑使用进程管理工具如Supervisor监控脚本
- Web环境注意脚本执行时间限制
- 分布式系统需要协调多个节点的心跳检测







