性能优化

PHP接口响应优化实验:从500ms到80ms

2024-04-15 | PHP 8.2 + Redis + MySQL
在Redis缓存实现中,采用了两级缓存策略:
// 获取笔记列表缓存
function getNotesFromCache($userId) {
    $cacheKey = "notes:user:{$userId}:".date('YmdH');
    $notes = $redis->get($cacheKey);
    
    if (!$notes) {
        // 缓存失效,从数据库获取
        $notes = $db->query("SELECT * FROM notes WHERE user_id = ?", $userId);
        
        // 设置缓存,过期时间600秒
        $redis->setex($cacheKey, 600, json_encode($notes));
    }
    
    return json_decode($notes, true);
}
批量查询优化前的代码:
// 优化前:循环查询标签
foreach ($notes as &$note) {
    $tags = $db->query("SELECT * FROM tags WHERE note_id = ?", $note['id']);
    $note['tags'] = $tags;
}
优化后的代码:
// 优化后:批量查询标签
$noteIds = array_column($notes, 'id');
$tagList = $db->query("SELECT * FROM tags WHERE note_id IN (?)", implode(',', $noteIds));

// 重组标签数据
$tagsMap = [];
foreach ($tagList as $tag) {
    $tagsMap[$tag['note_id']][] = $tag;
}

// 关联标签
foreach ($notes as &$note) {
    $note['tags'] = $tagsMap[$note['id']] ?? [];
}
接口响应时间降至80ms以内,服务器CPU使用率从70%降至35%。在并发用户数从100提升到500的情况下,接口响应时间仅从80ms增加到120ms,表现出良好的扩展性。 经验总结
  • 数据库查询优化是性能提升的基础,合理的索引设计能带来数量级的性能提升。
  • 缓存策略要根据业务场景灵活调整,对于更新频率不高的数据,缓存是提升性能的利器。
  • 减少数据库连接次数,将多次查询合并为一次批量查询,能有效降低数据库压力。
  • 后续计划 - 对其他高频接口进行同样的优化 - 引入APM工具(如Sentry)进行全链路性能监控 - 探索使用PHP OPcache和JIT进一步提升PHP执行效率
    分享至:

    相关学习推荐

    数据库

    MySQL慢查询定位实验:一条SQL从2s到200ms的优化

    2024-05-22
    查看详情
    性能优化

    PHP会话从文件到Redis的迁移实验

    2024-09-20
    查看详情