У меня есть выделенный сервер на 16 ГБ, на котором запущены 1 сайт wordpress и 1 сайт magento! Последний месяц я пытался оптимизировать mysql!
[корневой @ сервер ~] # ./mysqltuner.pl
MySQLTuner 1.7.19 - основные отчеты об ошибках Хайдена, запросы функций и загрузки на http://mysqltuner.com/ Запустите с '--help' для дополнительных опций и фильтрации вывода
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.7.28-log
[OK] Operating on 64-bit architecture
-------- Log file Recommendations ------------------------------------------------------------------
[OK] Log file /var/log/mysqld.log exists
[--] Log file: /var/log/mysqld.log(1K)
[OK] Log file /var/log/mysqld.log is readable.
[OK] Log file /var/log/mysqld.log is not empty
[OK] Log file /var/log/mysqld.log is smaller than 32 Mb
[OK] /var/log/mysqld.log doesn't contain any warning.
[!!] /var/log/mysqld.log contains 4 error(s).
[--] 0 start(s) detected in /var/log/mysqld.log
[--] 0 shutdown(s) detected in /var/log/mysqld.log
-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +ARCHIVE +BLACKHOLE +CSV -FEDERATED +InnoDB +MEMORY +MRG_MYISAM +MyISAM +PERFORMANCE_SCHEMA
[--] Data in MyISAM tables: 155.8M (Tables: 436)
[--] Data in InnoDB tables: 505.7M (Tables: 1302)
[--] Data in MEMORY tables: 0B (Tables: 34)
[OK] Total fragmented tables: 0
-------- Analysis Performance Metrics --------------------------------------------------------------
[--] innodb_stats_on_metadata: OFF
[OK] No stat updates during querying INFORMATION_SCHEMA.
продолжение ...
-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] There is no basic password file list!
-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined
-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 8h 22m 12s (4M q [133.105 qps], 69K conn, TX: 22G, RX: 870M)
[--] Reads / Writes: 98% / 2%
[--] Binary logging is disabled
[--] Physical Memory : 15.5G
[--] Max MySQL memory : 16.3G
[--] Other process memory: 0B
[--] Total buffers: 3.0G global + 272.6M per thread (50 max threads)
[--] P_S Max memory usage: 0B
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 11.8G (75.97% of installed RAM)
[!!] Maximum possible memory usage: 16.3G (105.15% of installed RAM)
[!!] Overall possible memory usage with other process exceeded memory
[OK] Slow queries: 0% (3K/4M)
[OK] Highest usage of available connections: 66% (33/50)
[OK] Aborted connections: 0.01% (5/69503)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[OK] Query cache is disabled by default due to mutex contention on multiprocessor machines.
[OK] Sorts requiring temporary tables: 0% (1K temp sorts / 1M sorts)
[!!] Joins performed without indexes: 3612
[!!] Temporary tables created on disk: 46% (318K on disk / 682K total)
[OK] Thread cache hit rate: 99% (679 created / 69K connections)
[!!] Table cache hit rate: 1% (4K open / 374K opened)
[OK] table_definition_cache(4940) is upper than number of tables(2052)
[OK] Open file limit used: 32% (3K/10K)
[OK] Table locks acquired immediately: 99% (2M immediate / 2M locks)
-------- Performance schema ------------------------------------------------------------------------
[--] Performance schema is disabled.
[--] Memory used by P_S: 0B
[--] Sys schema is installed.
-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.
продолжение
-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 23.9% (128M used / 536M cache)
[OK] Key buffer size / total MyISAM indexes: 512.0M/41.2M
[OK] Read Key buffer hit rate: 100.0% (395M cached / 59K reads)
[!!] Write Key buffer hit rate: 73.9% (55K cached / 40K writes)
-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 18
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 2.0G/505.7M
[OK] Ratio InnoDB log file size / InnoDB Buffer pool size: 256.0M * 2/2.0G should be equal to 25%
[OK] InnoDB buffer pool instances: 2
[--] Number of InnoDB Buffer Pool Chunk : 16 for 2 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 100.00% (488576089 hits/ 488600495 total)
[!!] InnoDB Write Log efficiency: 72.9% (141836 hits/ 194555 total)
[OK] InnoDB log waits: 0.00% (0 waits / 52719 writes)
-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.
-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.
-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.
-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.
-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] Binlog format: ROW
[--] XA support enabled: ON
[--] Semi synchronous replication Master: Not Activated
[--] Semi synchronous replication Slave: Not Activated
[--] This is a standalone server
продолжение
-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
Control error line(s) into /var/log/mysqld.log file
MySQL was started within the last 24 hours - recommendations may be inaccurate
Reduce your overall MySQL memory footprint for system stability
Dedicate this server to your database for highest performance.
Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
We will suggest raising the 'join_buffer_size' until JOINs not using indexes are found.
See https://dev.mysql.com/doc/internals/en/join-buffer-size.html
(specially the conclusions at the bottom of the page).
Temporary table size is already large - reduce result set size
Reduce your SELECT DISTINCT queries without LIMIT clauses
Increase table_open_cache gradually to avoid file descriptor limits
Read this before increasing table_open_cache over 64:
Read this before increasing for MariaDB https://mariadb.com/kb/en/library/optimizing-table_open_cache/
This is MyISAM only table_cache scalability problem, InnoDB not affected.
See more details here: https://bugs.mysql.com/bug.php?id=49177
This bug already fixed in MySQL 5.7.9 and newer MySQL versions.
Beware that open_files_limit (10000) variable
should be greater than table_open_cache (4940)
Performance schema should be activated for better diagnostics
Variables to adjust:
*** MySQL's maximum memory usage is dangerously high ***
*** Add RAM before increasing MySQL buffer variables ***
join_buffer_size (> 256.0M, or always use indexes with JOINs)
table_open_cache (> 4940)
performance_schema = ON enable PFS
================================================== =====================
[root@server ~]# ./tuning-primer.sh
-- MYSQL PERFORMANCE TUNING PRIMER --
- By: Matthew Montgomery -
MySQL Version 5.7.28-log x86_64
Uptime = 0 days 8 hrs 22 min 44 sec
Avg. qps = 133
Total Questions = 4014179
Threads Connected = 6
SLOW QUERIES
The slow query log is NOT enabled.
Current long_query_time = 0.500000 sec.
You have 3243 out of 4014251 that take longer than 0.500000 sec. to complete
Your long_query_time seems to be fine
BINARY UPDATE LOG
The binary update log is NOT enabled.
You will not be able to do point in time recovery
WORKER THREADS
Current thread_cache_size = 8
Current threads_cached = 6
Current threads_per_sec = 0
Historic threads_per_sec = 0
Your thread_cache_size is fine
MAX CONNECTIONS
Current max_connections = 50
Current threads_connected = 6
Historic max_used_connections = 33
The number of used connections is 66% of the configured maximum.
Your max_connections variable seems to be fine.
No InnoDB Support Enabled!
MEMORY USAGE
Max Memory Ever Allocated : 11.53 G
Configured Max Per-thread Buffers : 13.31 G
Configured Max Global Buffers : 2.75 G
Configured Max Memory Limit : 16.06 G
Physical Memory : 15.51 G
Max memory limit exceeds 90% of physical memory
KEY BUFFER
Current MyISAM index space = 41 M
Current key_buffer_size = 512 M
Key cache miss rate is 1 : 6641
Key buffer free ratio = 76 %
Your key_buffer_size seems to be fine
QUERY CACHE
Query cache is supported but not enabled
Perhaps you should set the query_cache_size
SORT OPERATIONS
Current sort_buffer_size = 16 M
Current read_rnd_buffer_size = 256 K
Sort buffer seems to be fine
JOINS
Current join_buffer_size = 256.00 M
You have had 3612 queries where a join could not use an index properly
join_buffer_size >= 4 M
This is not advised
You should enable "log-queries-not-using-indexes"
Then look for non indexed joins in the slow query log.
OPEN FILES LIMIT
Current open_files_limit = 10000 files
The open_files_limit should typically be set to at least 2x-3x
that of table_cache if you have heavy MyISAM usage.
Your open_files_limit value seems to be fine
TABLE CACHE
Current table_open_cache = 4940 tables
Current table_definition_cache = 4940 tables
You have a total of 1890 tables
You have 4928 open tables.
Current table_cache hit rate is 1%
, while 99% of your table cache is in use
You should probably increase your table_cache
TEMP TABLES
Current max_heap_table_size = 256 M
Current tmp_table_size = 256 M
Of 684967 temp tables, 31% were created on disk
Perhaps you should increase your tmp_table_size and/or max_heap_table_size
to reduce the number of disk-based temporary tables
Note! BLOB and TEXT columns are not allow in memory tables.
If you are using these columns raising these values might not impact your
ratio of on disk temp tables.
TABLE SCANS
Current read_buffer_size = 128 K
Current table scan ratio = 59 : 1
read_buffer_size seems to be fine
TABLE LOCKING
Current Lock Wait ratio = 1 : 1385
You may benefit from selective use of InnoDB.
If you have long running SELECT's against MyISAM tables and perform
frequent updates consider setting 'low_priority_updates=1'
If you have a high concurrency of inserts on Dynamic row-length tables
consider setting 'concurrent_insert=ALWAYS'.
==========================================================================
MY.CNF SETTING....
[mysqld]
local-infile=0
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
## Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
performance_schema=0
log_warnings=10
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
default-storage-engine=MyISAM
slow_query_log=1
slow_query_log_file=/var/log/mysql-slow.log
long_query_time=0.5
open_files_limit=10000
## Cache
table_open_cache=4940
table_definition_cache=4940
query_cache_type=0
query_cache_size=0
## Temp Tables
tmp_table_size=256M
max_heap_table_size=256M
## Networking
max_allowed_packet=268435456
interactive_timeout=75
wait_timeout=60
connect_timeout=60
max_connect_errors=10
max_connections=50
## MyISAM
join_buffer_size=256M
myisam_sort_buffer_size=128M
sort_buffer_size=16M
key_buffer_size=512M
## InnoDB
innodb_buffer_pool_size=2G
innodb_buffer_pool_instances=2
innodb_log_buffer_size=256M
innodb_log_file_size=256M
innodb_thread_concurrency=18
innodb_flush_log_at_trx_commit=2
innodb_file_per_table=1
================================================== =================
Согласно mysqltuner, join_buffer_size должен превышать 256M, и, как я искал, он не должен быть выше 2M, но я не уверен, нужно мне это или нет, одно я уверен, что я не могу оптимизировать magento или wordpress quires!
Плохо ли для производительности mysql иметь 256M? Не могли бы вы предложить мне что-нибудь!
Сколько из 16 ГБ действительно доступно MySQL?
Я бы сказал, что join_buffer_size
должно быть менее 1% от доступный ОЗУ. Он может быть выделен несколько раз несколькими подключениями. То же для max_heap_table_size
и tmp_table_size
.
Есть несколько признаков того, что у вас плохие индексы и / или плохая формулировка запросов. Давайте посмотрим на "медленный" запрос вместе с SHOW CREATE TABLE
.
Для начала рассмотрим в разделе my.cnf [mysqld]
innodb_thread_concurrency=0 # from 18 to allow OS to autolimit concurrency
innodb_log_file_size=1G # from 256M to reduce log file creation frequency
table_definition_cache=2000 # from ~4000 because you have less than 2000 tables
Есть ли причина для создания таблицы по умолчанию для MyISAM?
Учтите это, чтобы определить подходящий размер, войдите как root,
SET GLOBAL join_buffer_size=DEFAULT;
Через 1 час проверьте время отклика вашей системы. Если лучше,
REMOVE join_buffer_size from your configuration.
join_buffer_size используется только для COLUMNS of INTEREST для завершения соединения, а не для хранения ROW, как полагают некоторые люди.
Внутри этого URL https://dev.mysql.com/doc/refman/8.0/en/nested-loop-joins.html вы найдете этот пункт. В его буфере соединения хранятся только столбцы, представляющие интерес для соединения, а не целые строки.