在LNMP(Linux+Nginx+MySQL+PHP)环境中优化数据库查询是提高网站性能的关键。以下是一些有效的优化方法:
# my.cnf 或 my.ini 中的关键参数
[mysqld]
# 缓冲池大小(通常设为可用内存的50-70%)
innodb_buffer_pool_size = 4G
# 日志文件大小
innodb_log_file_size = 256M
# 连接数设置
max_connections = 200
thread_cache_size = 50
# 查询缓存(MySQL 8.0已移除)
# query_cache_size = 64M
# query_cache_type = 1
# 临时表设置
tmp_table_size = 64M
max_heap_table_size = 64M
# 其他InnoDB优化
innodb_flush_log_at_trx_commit = 2 # 对数据安全性要求不高时可设为2
innodb_flush_method = O_DIRECT
innodb_read_io_threads = 8
innodb_write_io_threads = 8
EXPLAIN
分析查询执行计划-- 查看未使用的索引
SELECT * FROM sys.schema_unused_indexes;
-- 查看索引统计信息
ANALYZE TABLE table_name;
SELECT *
,只查询需要的字段// PHP中的预处理示例
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
// 使用Redis缓存查询结果示例
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cacheKey = 'user_profile_' . $userId;
if ($redis->exists($cacheKey)) {
return json_decode($redis->get($cacheKey), true);
} else {
$data = fetchFromDatabase($userId);
$redis->setex($cacheKey, 3600, json_encode($data));
return $data;
}
-- 检查查询缓存状态
SHOW VARIABLES LIKE 'query_cache%';
-- 优化表
OPTIMIZE TABLE table_name;
-- 重建表(会锁表)
ALTER TABLE table_name ENGINE=InnoDB;
# my.cnf中启用慢查询日志
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1
log_queries_not_using_indexes = 1
性能监控工具:
分析工具:
通过综合应用这些优化策略,可以显著提高LNMP环境中数据库查询的性能和整体系统响应速度。