首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

解決 Windows Server 2008 R2 / 2012 上 PHP 連接 MySQL 緩慢的問題

     編輯:PHP 相關知識

為什麼 PHP 用 localhost 連本地 MySQL 會很慢?

在 Windows Server 2008 R2、2012 以及 Windows 7 等系統上,若 MySQL 設定檔 my.ini 指定了 bind-address=127.0.0.1,PHP 使用 localhost 連線本地資料庫會異常緩慢(超過 1 秒),而改用 127.0.0.1 則只需幾毫秒。這是因為 localhost 在 IPv6 環境下會優先解析為 ::1,導致連線嘗試 IPv6 後再 fallback 到 IPv4,造成嚴重延遲。

實測對比

<?php
$start = microtime(true);
$mysqli = new mysqli('127.0.0.1', 'root', '', 'mysql'); // 約 0.0025 秒
// $mysqli = new mysqli('localhost', 'root', '', 'mysql'); // 超過 1 秒,慢 400 倍
echo microtime(true) - $start;
?>

三種 bind-address 設定的行為差異

  • bind-address=127.0.0.1:只監聽 IPv4。PHP 用 localhost 連線極慢,用 127.0.0.1 正常。
  • bind-address=::1:只監聽 IPv6。PHP 用 localhost 正常,用 127.0.0.1 反而異常。
  • 註解掉 bind-address:同時監聽 IPv4 與 IPv6,localhost 與 127.0.0.1 皆正常。

解決方案

  1. 建議做法:在 my.ini 中註解或移除 bind-address,讓 MySQL 同時監聽 IPv4/IPv6,兼容所有連線方式。
  2. 快速應變:若無法修改 MySQL 設定,請在 PHP 程式(WordPress、phpMyAdmin 等)的資料庫主機欄位將 localhost 改為 127.0.0.1。

適用範圍

Windows 7、Windows Server 2008 R2、Windows Server 2012 及更新版本皆存在此現象。調整後可顯著提升 PHP 應用的資料庫連線效能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved