Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ตั้งค่า max_connections ใน MySQL แบบ Programmatic ด้วย SET GLOBAL


คำสั่งตั้งค่า max_connections ระหว่าง Runtime

ใช้ SET GLOBAL เปลี่ยนค่าได้ทันทีโดยไม่ต้อง Restart:

SET GLOBAL max_connections = 1000;

ตัวอย่างการใช้งาน

ตั้งค่าเป็น 1000

SET GLOBAL max_connections = 1000;
-- Query OK, 0 rows affected (0.04 sec)

ตรวจสอบค่าปัจจุบัน

SHOW VARIABLES LIKE 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 1000  |
+-----------------+-------+

ข้อจำกัดและข้อควรระวัง

  • ชั่วคราว: ค่าจะ Reset กลับค่าเดิมใน Config File เมื่อ Restart MySQL
  • สิทธิ์: ต้องมีสิทธิ์ SUPER หรือ SYSTEM_VARIABLES_ADMIN
  • ขอบเขต: ส่งผลต่อ Connection ใหม่เท่านั้น Connection เดิมไม่ได้รับผลกระทบ
  • Memory: แต่ละ Connection ใช้ Memory (thread_stack, sort_buffer, join_buffer, etc.) เพิ่ม max_connections ต้องคำนวณ RAM ให้พอ

ตั้งค่าคงถาวร (Persistent)

วิธีที่ 1: แก้ไข Config File (my.cnf / my.ini)

[mysqld]
max_connections = 1000

จากนั้น Restart MySQL Service

วิธีที่ 2: SET PERSIST (MySQL 8.0+)

SET PERSIST max_connections = 1000;

เขียนลง mysqld-auto.cnf (JSON) คงค่าหลัง Restart

คำนวณ max_connections ที่เหมาะสม

-- ดู Memory Usage ปัจจุบัน
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';

-- ประมาณ RAM ต่อ Connection
-- thread_stack (256KB) + sort_buffer_size (256KB) + join_buffer_size (256KB) + read_buffer_size (128KB) + ...
-- ประมาณ 1-4 MB ต่อ Connection ขึ้นกับ Workload

ดูสถานะ Connection

SHOW STATUS LIKE 'Threads_connected';      -- เชื่อมต่ออยู่
SHOW STATUS LIKE 'Max_used_connections';    -- สูงสุดที่เคยมีพร้อมกัน
SHOW STATUS LIKE 'Aborted_connects';        -- ล้มเหลว
SHOW STATUS LIKE 'Connection_errors%';      -- รายละเอียด Error