1. 程式人生 > >MySQL架構設計及效能優化

MySQL架構設計及效能優化

mysql變數

Variable_name   Value
auto_increment_increment    1
auto_increment_offset   1
autocommit  ON
automatic_sp_privileges ON
avoid_temporal_upgrade  OFF
back_log    90
basedir /usr/local/mysql
big_tables  OFF
bind_address    0.0.0.0
binlog_cache_size   32768
binlog_checksum CRC32
binlog_direct_non_transactional_updates OFF
binlog_error_action IGNORE_ERROR binlog_format ROW binlog_gtid_simple_recovery OFF binlog_max_flush_queue_time 0 binlog_order_commits ON binlog_row_image FULL binlog_rows_query_log_events OFF binlog_stmt_cache_size 32768 binlogging_impossible_mode IGNORE_ERROR block_encryption_mode aes-128
-ecb bulk_insert_buffer_size 8388608 character_set_client utf8 character_set_connection utf8 character_set_database utf8 character_set_filesystem binary character_set_results utf8 character_set_server utf8 character_set_system utf8 character_sets_dir /home/imooc/mysql5625/share/charsets/ collation_connection utf8_general_ci collation_database utf8_general_ci collation_server utf8_general_ci completion_type NO_CHAIN concurrent_insert AUTO
connect_timeout 10 core_file OFF datadir /usr/local/mysql/data/ date_format %Y-%m-%d datetime_format %Y-%m-%d %H:%i:%s default_storage_engine InnoDB default_tmp_storage_engine InnoDB default_week_format 0 delay_key_write ON delayed_insert_limit 100 delayed_insert_timeout 300 delayed_queue_size 1000 disconnect_on_expired_password ON div_precision_increment 4 end_markers_in_json OFF enforce_gtid_consistency ON eq_range_index_dive_limit 10 event_scheduler OFF expire_logs_days 7 explicit_defaults_for_timestamp OFF flush OFF flush_time 0 foreign_key_checks ON ft_boolean_syntax + -><()~*:""&| ft_max_word_len 84 ft_min_word_len 4 ft_query_expansion_limit 20 ft_stopword_file (built-in) general_log OFF general_log_file /usr/local/mysql/data/localhost.log group_concat_max_len 1024 gtid_executed 98c4c03e-d495-11e5-b7c0-080027ca20fd:1-15156 gtid_mode ON gtid_owned gtid_purged have_compress YES have_crypt YES have_dynamic_loading YES have_geometry YES have_openssl DISABLED have_profiling YES have_query_cache YES have_rtree_keys YES have_ssl DISABLED have_symlink YES host_cache_size 328 hostname localhost.localdomain ignore_builtin_innodb OFF ignore_db_dirs init_connect init_file init_slave innodb_adaptive_flushing ON innodb_adaptive_flushing_lwm 10 innodb_adaptive_hash_index ON innodb_adaptive_max_sleep_delay 150000 innodb_additional_mem_pool_size 8388608 innodb_api_bk_commit_interval 5 innodb_api_disable_rowlock OFF innodb_api_enable_binlog OFF innodb_api_enable_mdl OFF innodb_api_trx_level 0 innodb_autoextend_increment 64 innodb_autoinc_lock_mode 1 innodb_buffer_pool_dump_at_shutdown OFF innodb_buffer_pool_dump_now OFF innodb_buffer_pool_filename ib_buffer_pool innodb_buffer_pool_instances 8 innodb_buffer_pool_load_abort OFF innodb_buffer_pool_load_at_startup OFF innodb_buffer_pool_load_now OFF innodb_buffer_pool_size 134217728 innodb_change_buffer_max_size 25 innodb_change_buffering all innodb_checksum_algorithm innodb innodb_checksums ON innodb_cmp_per_index_enabled OFF innodb_commit_concurrency 0 innodb_compression_failure_threshold_pct 5 innodb_compression_level 6 innodb_compression_pad_pct_max 50 innodb_concurrency_tickets 5000 innodb_data_file_path ibdata1:128M:autoextend innodb_data_home_dir innodb_disable_sort_file_cache OFF innodb_doublewrite ON innodb_fast_shutdown 1 innodb_file_format Antelope innodb_file_format_check ON innodb_file_format_max Antelope innodb_file_per_table ON innodb_flush_log_at_timeout 1 innodb_flush_log_at_trx_commit 2 innodb_flush_method O_DIRECT innodb_flush_neighbors 1 innodb_flushing_avg_loops 30 innodb_force_load_corrupted OFF innodb_force_recovery 0 innodb_ft_aux_table innodb_ft_cache_size 8000000 innodb_ft_enable_diag_print OFF innodb_ft_enable_stopword ON innodb_ft_max_token_size 84 innodb_ft_min_token_size 3 innodb_ft_num_word_optimize 2000 innodb_ft_result_cache_limit 2000000000 innodb_ft_server_stopword_table innodb_ft_sort_pll_degree 2 innodb_ft_total_cache_size 640000000 innodb_ft_user_stopword_table innodb_io_capacity 20000 innodb_io_capacity_max 40000 innodb_large_prefix OFF innodb_lock_wait_timeout 60 innodb_locks_unsafe_for_binlog OFF innodb_log_buffer_size 16777216 innodb_log_compressed_pages ON innodb_log_file_size 134217728 innodb_log_files_in_group 2 innodb_log_group_home_dir ./ innodb_lru_scan_depth 1024 innodb_max_dirty_pages_pct 75 innodb_max_dirty_pages_pct_lwm 0 innodb_max_purge_lag 0 innodb_max_purge_lag_delay 0 innodb_mirrored_log_groups 1 innodb_monitor_disable innodb_monitor_enable innodb_monitor_reset innodb_monitor_reset_all innodb_old_blocks_pct 37 innodb_old_blocks_time 1000 innodb_online_alter_log_max_size 134217728 innodb_open_files 8192 innodb_optimize_fulltext_only OFF innodb_page_size 16384 innodb_print_all_deadlocks OFF innodb_purge_batch_size 300 innodb_purge_threads 1 innodb_random_read_ahead OFF innodb_read_ahead_threshold 56 innodb_read_io_threads 8 innodb_read_only OFF innodb_replication_delay 0 innodb_rollback_on_timeout OFF innodb_rollback_segments 128 innodb_sort_buffer_size 1048576 innodb_spin_wait_delay 6 innodb_stats_auto_recalc ON innodb_stats_method nulls_equal innodb_stats_on_metadata OFF innodb_stats_persistent ON innodb_stats_persistent_sample_pages 20 innodb_stats_sample_pages 8 innodb_stats_transient_sample_pages 8 innodb_status_output OFF innodb_status_output_locks OFF innodb_strict_mode OFF innodb_support_xa ON innodb_sync_array_size 1 innodb_sync_spin_loops 30 innodb_table_locks ON innodb_thread_concurrency 0 innodb_thread_sleep_delay 10000 innodb_undo_directory . innodb_undo_logs 128 innodb_undo_tablespaces 0 innodb_use_native_aio OFF innodb_use_sys_malloc ON innodb_version 5.6.25 innodb_write_io_threads 24 interactive_timeout 18800 join_buffer_size 1048576 keep_files_on_create OFF key_buffer_size 33554432 key_cache_age_threshold 300 key_cache_block_size 1024 key_cache_division_limit 100 large_files_support ON large_page_size 0 large_pages OFF lc_messages en_US lc_messages_dir /home/imooc/mysql5625/share/ lc_time_names en_US license GPL local_infile ON lock_wait_timeout 31536000 locked_in_memory OFF log_bin ON log_bin_basename /usr/local/mysql/sql_log/mysql-bin log_bin_index /usr/local/mysql/sql_log/mysql-bin.index log_bin_trust_function_creators OFF log_bin_use_v1_row_events OFF log_error /usr/local/mysql/sql_log/mysql-error.log log_output FILE log_queries_not_using_indexes ON log_slave_updates ON log_slow_admin_statements OFF log_slow_slave_statements OFF log_throttle_queries_not_using_indexes 0 log_warnings 2 long_query_time 10.000000 low_priority_updates OFF lower_case_file_system OFF lower_case_table_names 0 master_info_repository TABLE master_verify_checksum OFF max_allowed_packet 104857600 max_binlog_cache_size 18446744073709547520 max_binlog_size 1048576000 max_binlog_stmt_cache_size 18446744073709547520 max_connect_errors 1000000 max_connections 200 max_delayed_threads 20 max_digest_length 1024 max_error_count 64 max_heap_table_size 33554432 max_insert_delayed_threads 20 max_join_size 18446744073709551615 max_length_for_sort_data 16384 max_prepared_stmt_count 16382 max_relay_log_size 0 max_seeks_for_key 18446744073709551615 max_sort_length 1024 max_sp_recursion_depth 0 max_tmp_tables 32 max_user_connections 0 max_write_lock_count 18446744073709551615 metadata_locks_cache_size 1024 metadata_locks_hash_instances 8 min_examined_row_limit 0 multi_range_count 256 myisam_data_pointer_size 6 myisam_max_sort_file_size 9223372036853727232 myisam_mmap_size 18446744073709551615 myisam_recover_options BACKUP,FORCE myisam_repair_threads 1 myisam_sort_buffer_size 8388608 myisam_stats_method nulls_unequal myisam_use_mmap OFF net_buffer_length 16384 net_read_timeout 30 net_retry_count 10 net_write_timeout 60 new OFF old OFF old_alter_table OFF old_passwords 0 open_files_limit 65535 optimizer_prune_level 1 optimizer_search_depth 62 optimizer_switch index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,index_condition_pushdown=on,mrr=on,mrr_cost_based=on,block_nested_loop=on,batched_key_access=off,materialization=on,semijoin=on,loosescan=on,firstmatch=on,subquery_materialization_cost_based=on,use_index_extensions=on optimizer_trace enabled=off,one_line=off optimizer_trace_features greedy_search=on,range_optimizer=on,dynamic_range=on,repeated_subselect=on optimizer_trace_limit 1 optimizer_trace_max_mem_size 16384 optimizer_trace_offset -1 performance_schema ON performance_schema_accounts_size 100 performance_schema_digests_size 10000 performance_schema_events_stages_history_long_size 10000 performance_schema_events_stages_history_size 10 performance_schema_events_statements_history_long_size 10000 performance_schema_events_statements_history_size 10 performance_schema_events_waits_history_long_size 10000 performance_schema_events_waits_history_size 10 performance_schema_hosts_size 100 performance_schema_max_cond_classes 80 performance_schema_max_cond_instances 9092 performance_schema_max_file_classes 50 performance_schema_max_file_handles 32768 performance_schema_max_file_instances 100824 performance_schema_max_mutex_classes 200 performance_schema_max_mutex_instances 43160 performance_schema_max_rwlock_classes 40 performance_schema_max_rwlock_instances 25376 performance_schema_max_socket_classes 10 performance_schema_max_socket_instances 420 performance_schema_max_stage_classes 150 performance_schema_max_statement_classes 168 performance_schema_max_table_handles 8192 performance_schema_max_table_instances 12500 performance_schema_max_thread_classes 50 performance_schema_max_thread_instances 500 performance_schema_session_connect_attrs_size 512 performance_schema_setup_actors_size 100 performance_schema_setup_objects_size 100 performance_schema_users_size 100 pid_file /usr/local/mysql/data/mysqld.pid plugin_dir /usr/local/mysql/lib/plugin/ port 3306 preload_buffer_size 32768 profiling OFF profiling_history_size 15 protocol_version 10 query_alloc_block_size 8192 query_cache_limit 1048576 query_cache_min_res_unit 4096 query_cache_size 0 query_cache_type OFF query_cache_wlock_invalidate OFF query_prealloc_size 8192 range_alloc_block_size 4096 read_buffer_size 2097152 read_only OFF read_rnd_buffer_size 2097152 relay_log /usr/local/mysql/sql_log/mysqld-relay-bin relay_log_basename /usr/local/mysql/sql_log/mysqld-relay-bin relay_log_index /usr/local/mysql/sql_log/mysqld-relay-bin.index relay_log_info_file relay-log.info relay_log_info_repository TABLE relay_log_purge ON relay_log_recovery OFF relay_log_space_limit 0 report_host report_password report_port 3306 report_user rpl_stop_slave_timeout 31536000 secure_auth ON secure_file_priv server_id 101 server_id_bits 32 server_uuid 98c4c03e-d495-11e5-b7c0-080027ca20fd show_old_temporals OFF simplified_binlog_gtid_recovery OFF skip_external_locking ON skip_name_resolve ON skip_networking OFF skip_show_database OFF slave_allow_batching OFF slave_checkpoint_group 512 slave_checkpoint_period 300 slave_compressed_protocol OFF slave_exec_mode STRICT slave_load_tmpdir /tmp slave_max_allowed_packet 1073741824 slave_net_timeout 3600 slave_parallel_workers 0 slave_pending_jobs_size_max 16777216 slave_rows_search_algorithms TABLE_SCAN,INDEX_SCAN slave_skip_errors OFF slave_sql_verify_checksum ON slave_transaction_retries 10 slave_type_conversions slow_launch_time 2 slow_query_log OFF slow_query_log_file /usr/local/mysql/sql_log/slow-mysql.log socket /usr/local/mysql/data/mysql.sock sort_buffer_size 2097152 sql_auto_is_null OFF sql_big_selects ON sql_buffer_result OFF sql_log_bin ON sql_log_off OFF sql_mode STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION sql_notes ON sql_quote_show_create ON sql_safe_updates OFF sql_select_limit 18446744073709551615 sql_slave_skip_counter 0 sql_warnings OFF ssl_ca ssl_capath ssl_cert ssl_cipher ssl_crl ssl_crlpath ssl_key storage_engine InnoDB stored_program_cache 256 sync_binlog 1 sync_frm ON sync_master_info 10000 sync_relay_log 10000 sync_relay_log_info 10000 system_time_zone CST table_definition_cache 4096 table_open_cache 4096 table_open_cache_instances 1 thread_cache_size 2048 thread_concurrency 24 thread_handling one-thread-per-connection thread_stack 524288 time_format %H:%i:%s time_zone SYSTEM timed_mutexes OFF tmp_table_size 33554432 tmpdir /tmp transaction_alloc_block_size 8192 transaction_prealloc_size 4096 tx_isolation REPEATABLE-READ tx_read_only OFF unique_checks ON updatable_views_with_limit YES version 5.6.25-log version_comment Source distribution version_compile_machine x86_64 version_compile_os Linux wait_timeout 18800

1 儲存引擎

myIsam引擎
- 非事務型應用
- 只讀類應用
- 空間類應用

.MYD是MyISAM表的資料檔案的副檔名
.MYI是MyISAM表的索引的副檔名

Innodb引擎
使用表空間儲存資料
innoDB_file_per_table
on: 獨立表空間 name.ibd
off: 系統表空間 iddata1

show variables like 'innodb_file_per_table'

/*當你刪除資料時,mysql並不會回收,被已刪除資料的佔據的儲存空間,以及索引位。而是空在那裡,而是等待新的資料來彌補這個空缺,這樣就有一個缺少,如果一時半會,沒有資料來填補這個空缺,那這樣就太浪費資源了。所以對於寫比較頻煩的表,要定期進行optimize,一個月一次,看實際情況而定了*/
mysql> optimize table ad_visit_history;      

系統表空間和獨立表空間如何選擇

  • 系統表空間無法簡單的收縮檔案大小,系統表空間會產生IO瓶頸
  • 獨立表空間可以利用optimize table命令收縮檔案大小,多個檔案可以同時重新整理資料

建議:對Innodb使用獨立表空間

錶轉移的步驟

  1. mysqldump匯出資料庫表資料
  2. 停止MySQL服務,修改引數,並刪除Innodb相關檔案
  3. 重啟MYSQL服務,重建系統表空間
  4. 重新匯入資料

其他儲存引擎

/*使用archive,其中arz儲存資料,frm儲存表結構,不支援刪除更新操作*/
/*使用場景,日誌和資料採集,不適合oltp*/
create table myarchive(id int auto_increment not null,c1 varchar(10),key(id)) engine=archive;

/*memory儲存引擎,資料存在記憶體中,表結構存在磁碟中,IO效率很高,支援HASH和Btree,不支援blob,使用表級鎖*/
create table mymemory(id int,c1 varchar(10),c2 char(10)) engine=memory;

[email protected]:/var/lib/mysql/sakila# ls -lh mymemory*
-rw-r----- 1 mysql mysql 8.5K Dec 21 20:52 mymemory.frm

mysql> create table mymemory(id int,c1 varchar(10),c2 char(10)) engine=memory;
Query OK, 0 rows affected (0.01 sec)


mysql> create index idx_c2 using btree on mymemory(c2);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show index from mymemory\G;
*************************** 1. row ***************************
        Table: mymemory
   Non_unique: 1
     Key_name: idx_c1
 Seq_in_index: 1
  Column_name: c1
    Collation: NULL
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: HASH
      Comment: 
Index_comment: 
*************************** 2. row ***************************
        Table: mymemory
   Non_unique: 1
     Key_name: idx_c2
 Seq_in_index: 1
  Column_name: c2
    Collation: A
  Cardinality: NULL
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: BTREE
      Comment: 
Index_comment: 
2 rows in set (0.00 sec)
/*下圖可知,memory儲存引擎的表都是固定長度*/
mysql> show table status like 'mymemory'\G;
*************************** 1. row ***************************
           Name: mymemory
         Engine: MEMORY
        Version: 10
     Row_format: Fixed
           Rows: 0
 Avg_row_length: 26
    Data_length: 0
Max_data_length: 4406116
   Index_length: 0
      Data_free: 0
 Auto_increment: NULL
    Create_time: 2017-12-21 20:56:43
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options: 
        Comment: 
1 row in set (0.01 sec)
/*用於查詢對映表,儲存資料分析的中間表,快取週期性聚合資料的結果表*/

這裡寫圖片描述

/*Federated儲存引擎,本地不儲存資料,資料儲存在遠端伺服器,本地儲存表結構和遠端伺服器的連線資訊,預設禁止*/
mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
| CSV                | YES     | CSV storage engine                                             | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                             | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                         | NO           | NO   | NO         |
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and foreign keys     | YES          | YES  | YES        |
| FEDERATED          | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.01 sec)


/*編輯cnf檔案,加入federated引擎支援*/
federated=1

grant select,update,insert,delete on yuejuan.tiankongti to fred[email protected]'120.95.132.228' indetified by '123456'

/*建立同名表*/
create table `name`() engine=federated connection ='mysql://user_name:[email protected]:3306/db/table'

/*使用場景*/
並不適合生產環境,偶爾的統計分析或者實驗條件

事務支援:Innodb
備份:Innodb可以線上熱備份,崩潰恢復更好
mysqldump為邏輯備份,並且會加鎖,故不是熱備份方案
儲存引擎在一個數據庫最好統一。

MySQL伺服器引數

[email protected]:/var/lib# mysqld --help --verbose|grep -A 1 'Default options'
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf 

記憶體相關引數

  1. 確定可以使用的記憶體上限
  2. 確定MySQL每個連線所使用的記憶體,sort_buffer_size join_buffer_size read_buffer_size read_rnd_buffer_size->針對執行緒設定的快取大小
  3. 確定需要為作業系統保留的記憶體
  4. 如何為快取池分配記憶體,Innodb_buffer_pool_size 不僅快取索引,也會快取資料。innodb的效能嚴重依賴這個引數,Innodb_buffer_pool_size=總記憶體-(每個執行緒所需要的記憶體*連線數)-系統保留記憶體。
  5. key_buffer_size 主要針對myIsam,快取索引。因為mysql系統表仍然使用MyIsam引擎,所以該size必須配置。

I/O相關配置引數

  1. innodb I/O相關配置,Innodb_log_file_size 控制單個日誌檔案大小
  2. Innodb_flush_log_at_trx_commit:2 每次事務提交,執行log資料寫入到cache,每秒執行一次flush log到磁碟。好處是如果mysql程序崩潰了,設定為2時,不會丟失任何資料。只有伺服器崩潰了,資料才會損失。

2 基準測試

測試目的

  • 建立伺服器效能基準線
  • 模擬比當前系統更高的負載,以找出系統的擴充套件瓶頸
  • 測試不同的硬體軟體和作業系統配置
  • 證明新的硬體裝置是否配置正確

如何基準測試

  • 系統入口測試
  • 單獨對MySQL進行基礎測試
    • TPS
    • QPS
    • 響應時間
    • 併發量

基準測試的步驟

#!/bin/bash
INTERVAL=5
PREFIX=/home/imooc/benchmarks/$INTERVAL-sec-status
RUNFILE=/home/imooc/benchmarks/running
echo "1" > $RUNFILE
MYSQL=/usr/local/mysql/bin/mysql
$MYSQL -e "show global variables" >> mysql-variables
while test -e $RUNFILE; do
    file=$(date +%F_%I)
    sleep=$(date +%s.%N | awk '{print 5 - ($1 % 5)}')
    sleep $sleep
    ts="$(date +"TS %s.%N %F %T")"
    loadavg="$(uptime)"
    echo "$ts $loadavg" >> $PREFIX-${file}-status
    $MYSQL -e "show global status" >> $PREFIX-${file}-status &
    echo "$ts $loadavg" >> $PREFIX-${file}-innodbstatus
    $MYSQL -e "show engine innodb status" >> $PREFIX-${file}-innodbstatus &
    echo "$ts $loadavg" >> $PREFIX-${file}-processlist
    $MYSQL -e "show full processlist\G" >> $PREFIX-${file}-processlist &
    echo $ts
done
echo Exiting because $RUNFILE does not exists

常用的測試工具
MySQLslap:模擬伺服器負載,輸出統計資訊;指定或者自動生成查詢語句;

--auto-generate-sql##自動生成sql指令碼測試
--auto-generate-sql-add-autoincremnet ##生成的表中增加自增ID
--auto-generate-sql-load-type  ##指定測試中使用的查詢型別
--auto-generate-sql-write-number ##指定初始化資料時生成的資料量
--concurrency                    ##指定併發執行緒的數量
--engine                        ##指定需要測試的表的儲存引擎,逗號分隔
--no-drop                       ##指定不清理資料
--iterations                    #指定測試執行的次數
--number-of-queries ##指定每一個執行緒執行的查詢數量
--number-int-cols ##指定測試表中包含的int型別列的數量
--number-char-cols ##指定表中包含的varchar型別的數量
--create-schema   ##指定用於執行測試的資料庫的名字
--query
--only-print

mysqlslap -u chuyao -p --concurrency=1,50,100,500 --iterations=3 --number-int-cols=5 --number-char-cols=5 --auto-generate-sql --auto-generate-sql-add-autoincrement --engine=myisam,innodb --number-of-queries=10 --create-schema=db14 --only-print >1.sql

MySQL檔案的預設位置

/var/run/mysqld/mysqld.sock
/usr/bin                 客戶端程式和指令碼  
/usr/sbin                mysqld 伺服器  
/var/lib/mysql           日誌檔案,資料庫  [重點要知道這個]  
/usr/share/doc/packages  文件  
/usr/include/mysql       包含( 頭) 檔案  
/usr/lib/mysql           庫  
/usr/share/mysql         錯誤訊息和字符集檔案  
/usr/share/sql-bench     基準程式 

sysbench安裝

apt-get install automake
apt-get install libtool
./autogen.sh
./configure --with-mysql-includes=/usr/include/mysql/ \--with-mysql-libs=/usr/lib/mysql
./configure && make && make install
make && make install

sysbench --test ##用於制定執行的測試型別,支援以下引數
fileio
cpu
memory
Oltp  測試要指定具體的lua指令碼

--mysql-db 用於指定執行資料庫名
--mysql-table-engine 用於指定使用的儲存引擎
--oltp-table-count 執行測試的表的數量
--oltp-table-size 執行測試的每個表的資料行數
--num-threads 指定併發執行緒的數量
--max-time 指定最大的測試時間
prepare 用於準備測試資料
run 用於實際測試


sysbench --test=fileio --file-total-size=1G prepare

sysbench --test=./oltp.lua --mysql-table-engine=innodb --oltp-table-size=10000 --mysql-db=sysbench2 --mysql-user=sbtest --mysql-password=123456 --oltp-tables-count=10 --mysql-socket=/var/run/mysqld/mysqld.sock prepare

3 主從複製

mysql> show variables like 'binlog_format'
mysql> set session binlog_format=statement;
mysql> set session binlog_format=row;##基於row的日誌可以避免主從複製不一致的情況,基於段的SQL只會記錄SQL語句,基於行的會記錄每一行的修改
##誤操作修改了資料庫時,我們可以分析二進位制日誌反向處理恢復資料
root@ubuntu:/var/lib/mysql# mysqlbinlog log-bin.000001   ##檢視日誌
mysql> set session binlog_format=MIXED;
mysql> show variables like 'binlog_row_image';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| binlog_row_image | FULL  |
+------------------+-------+

注意,啟用二進位制日誌需要在cnf檔案配置路徑

log-bin=/var/lib/mysql/log-bin.log

基於SQL語名的複製(SBR)
優點:日誌量少,不強制要求主從資料庫表定義,相比於行複製更為靈活
缺點:不保證主從一致,從伺服器需要更多的行鎖

mysql複製工作方式

  1. 主伺服器將變更寫入二進位制日誌
  2. 從伺服器讀取主伺服器的日誌變更寫入relay_log中
  3. 在從伺服器上重放relay_log中的日誌

    基於SQL段的日誌是在從資料庫重新執行記錄的SQL
    基於行的日誌是在從資料庫上直接應用資料庫行的修改

基於日誌的複製、基於GTID的複製

影響主從延遲的因素

  1. 主庫寫入二進位制日誌的時間
    1. 控制主庫的事務大小,分割大事務
  2. 二進位制日誌傳輸時間
    1. 使用mixed日誌格
    2. 設定 binlog_row_image=minimal;
  3. 從伺服器序列
    1.使用多執行緒複製

    如何配置多執行緒複製

stop slave;
set global slave_parallel_type='logic_clock';
set global slave_parallel_workers=4;//併發執行緒的數量
start slave;

主從複製常見錯誤
主庫或者從庫意外宕機引起的錯誤:
*使用跳過二進位制事件
注入空事務的方式先恢復中斷的複製鏈路
對比主從資料*
主庫上的二進位制檔案日誌損壞

高可用架構

  • 建立完善的監控和報警
  • 對備份資料進行恢復測試
  • 正確配置資料庫環境
  • 對不需要的資料歸檔和清理
  • 避免出現單點故障
  • 主從切換及故障轉移

避免單點故障:DRDB磁碟複製方式
這裡寫圖片描述

MMM架構
主主複製
監控MySQL主從複製健康狀況,主伺服器宕機時進行故障轉移並配置其他從伺服器對新主伺服器的複製
這裡寫圖片描述

架構部署步驟:

  1. 配置主主複製和主從同步叢集
  2. 安裝主從節點所需要的支援包
  3. 安裝及配置MMM工具集
  4. 執行MMM監控服務

MMM框架的優點:

  1. 開源+Perl
  2. 主從複製延遲時會自動切換
  3. MMM框架提供了從伺服器的延遲監控
  4. 提供了主伺服器故障轉移之後的重新同步功能

MMM框架的缺點:

  1. 不支援MYSQL新的複製功能
  2. 沒有讀負載均衡的功能
  3. 存在單點故障

MHA架構
主DB不可用時,從多個伺服器中選舉出新的主資料庫伺服器

讀寫分離要解決的是如何在複製叢集的不同角色上,執行不同的SQL語句。
讀的負載均衡解決的是相同角色資料庫如何共同分擔相同的負載。

4 資料庫索引優化

索引列上不能使用表示式或者函式

select ---from produ**ct
where to_days(out_dat**e)-to_days(current_date)<=30

/*優化策略*/
select ---- from product
where out_date<date_add(current_date,interval 30 day)

聯合索引

  1. 經常被使用的列優先
  2. 選擇性高的列優先

覆蓋索引

use sakila;

mysql> explain select language_id from film where language_id=1\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: film
   partitions: NULL
         type: ref
possible_keys: idx_fk_language_id
          key: idx_fk_language_id
      key_len: 1
          ref: const
         rows: 1003
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.00 sec)

ERROR: 
No query specified

mysql> explain select *  from film where language_id=1\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: film
   partitions: NULL
         type: ALL
possible_keys: idx_fk_language_id
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 1000
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)

ERROR: 
No query specified

mysql資料庫的innodb表會自動加入二級索引

mysql> show create table actor \G;
*************************** 1. row ***************************
       Table: actor
Create Table: CREATE TABLE `actor` (
  `actor_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`actor_id`),
  KEY `idx_actor_last_name` (`last_name`)
) ENGINE=InnoDB AUTO_INCREMENT=201 DEFAULT CHARSET=utf8
1 row in set (0.02 sec)

ERROR: 
No query specified

mysql> explain select actor_id,last_name from actor where last_name='Joe'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: actor
   partitions: NULL
         type: ref
possible_keys: idx_actor_last_name
          key: idx_actor_last_name
      key_len: 137
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.04 sec)

使用索引掃描來優化排序

  1. 索引的列順序和order by子句的順序完全一致
  2. 索引中所有列的方向和order by子句完全一致
  3. order by中的欄位完全在關聯表中的第一張表

模擬hash索引

alter table film add title_md5 varchar(32);
Query OK, 0 rows affected (1.45 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> update film set title_md5=md5(title);
Query OK, 1003 rows affected (0.40 sec)
Rows matched: 1003  Changed: 1003  Warnings: 0

mysql> create index idx_md5 on film(title_md5);
Query OK, 0 rows affected (0.10 sec)
Records: 0  Duplicates: 0  Warnings: 0

explain select * from film where title_md5=md5('egg igby') and title ='egg igby';

4 資料庫查詢優化

獲取問題SQL

  1. 慢查詢日誌
  2. 實時監控

慢查詢日誌

slow_query_log //啟動停止記錄慢查日誌
slow_query_log_file //指定慢查日誌的儲存及檔案,最好將慢查日誌和資料檔案分在不同的分割槽之中
long_query_time //指定記錄慢查日誌SQL執行時間的閾值,預設10秒,改為0.001秒比價合適
log_queries_not_using_indexes //是否記錄未使用索引的SQL

和二進位制日誌不同,慢查詢日誌會記錄所有符合條件的SQL,包括查詢語句和資料修改語句

使用sysbench生成慢查詢日誌

[email protected]:/home/ubuntu/Desktop/軟體/sysbench-0.5/sysbench/tests/db# sysbench --test=./oltp.lua --mysql-table-engine=innodb --oltp-table-size=10000 --mysql-db=sysbench_test --mysql-user=root --mysql-password=123456 --oltp-tables-count=10 --mysql-socket=/var/run/mysqld/mysqld.sock run
sysbench 0.5:  multi-threaded system evaluation benchmark

Running the test 
            
           

相關推薦

MySQL架構設計效能優化

mysql變數 Variable_name Value auto_increment_increment 1 auto_increment_offset 1 autocommit ON automatic_sp_privileges ON

電商搜尋引擎的架構設計效能優化

轉載:https://blog.csdn.net/hu948162999/article/details/78861860 首先,我想說的是電商搜尋引擎和普通的搜尋引擎有很大的差別,因為電商搜尋引擎主要是解決使用者要“買什麼”,而通用搜索引擎主要是解決使用者“搜什麼

MySQL邏輯架構效能優化原理

  說起MySQL的查詢優化,相信所有人都瞭解一些最簡單的技巧:不能使用SELECT *、不使用NULL欄位、合理建立索引、為欄位選擇合適的資料型別….. 你是否真的理解這些優化技巧?是否理解其背後的工

高效能可擴充套件MySQL資料庫設計架構優化 電商專案

第1章 資料庫開發規範的制定俗話說:“沒有規矩不成方圓”。這一章,我們就先來制定資料庫開發的各種規範,包括:資料庫命名規範、資料庫基本設計規範、資料庫索引設計規範、資料庫欄位設計規範、SQL開發規範以及資料庫操作規範。通過這些規範的制定可以指導並規範我們後續的開發工作,為我們

Lamp、MySQL架構介紹MySQL的安裝

20180523一、Lamp架構介紹 1?是一個簡寫,它包含了四個東西:Linux 操作系統;Apache(httpd) 是一個web服務軟件;MySQL 數據存儲軟件;PHP 腳本語言,和shell類似,比shell復雜,通常用來做網站; 2?httpd 、PHP、MySQL三者是如何工作的,用戶瀏覽器

這些Mysql基礎設計思路以及優化思路我都給你總結好了

%s mit 標記 總結 業務 增加 二叉 索引 基礎 1、定長和不定長要區分開   2、不常用的列和常用的列分開存   3、增加冗余,反範式化   4、btree索引,就是用樹形結構存儲在磁盤上,其中操作是用2分發,找一個中間點,然後把大比這個大的分在一邊,小的放在一邊,

菜鳥要做架構師——java效能優化之for迴圈

完成同樣的功能,用不同的程式碼來實現,效能上可能會有比較大的差別,所以對於一些效能敏感的模組來說,對程式碼進行一定的優化還是很有必要的。今天就來說一下java程式碼優化的事情,今天主要聊一下對於for(while等同理)迴圈的優化。 作為三大結構之一的迴圈,在我們編寫程式碼的時候會經常用到。

MySQL分頁查詢效能優化

當需要從資料庫查詢的表有上萬條記錄的時候,一次性查詢所有結果會變得很慢,特別是隨著資料量的增加特別明顯,這時需要使用分頁查詢。對於資料庫分頁查詢,也有很多種方法和優化的點。下面簡單說一下我知道的一些方法。 準備工作 為了對下面列舉的一些優化進行測試,下面針對已有的一張表進行說明。 表名:order

【redis常用的鍵值操作效能優化

服務端 啟動redis服務   { // -a:指定密碼 -h:指定主機 -p:指定埠 }   //讓redis 服務中斷崩潰 //儲存和關閉   //後臺備份 //設定登入密碼 //redis-benchmark :效能測試 &

秒殺系統的架構設計實現

秒殺場景在電商平臺是十分常見的,這種營銷活動往往具有時間短,併發量大的特點。 關於資料庫效能 TPS:資料庫每秒執行的事務數。 QPS:資料庫每秒執行的SQL數。 對於msql資料庫,8核CPU16G記憶體通常TPS:1000 QPS:20000 系統邏輯梳理 使用者介面點選

MySql設計相關規範

一、資料庫設計思維    1.  新增必要的(冗餘)欄位        像“建立時間”、“修改時間”、“備註”、“操作使用者IP”和一些用於其他需求(如統計)的欄位等,在每張表中必須都要有,不是 說只有系統中用到的資料才會存到

MySQL提升課程 全面講解MySQL架構設計 打造扛得住的MySQL資料庫架構

第1章 例項和故事決定電商11大促成敗的各個關鍵因素。1-1 什麼決定了電商雙11大促的成敗1-2 在雙11大促中的資料庫伺服器1-3 在大促中什麼影響了資料庫效能1-4 大表帶來的問題1-5 大事務帶來的問題 第2章 什麼影響了MySQL效能詳細介紹影響效能各個因素,包括硬體、作業系統等等。2-1 影響效

電子商城後臺系統(二):系統架構設計系統介紹

在寫一個程式之前,需要在大腦中對整個系統有一個初步的規劃,對於系統的功能模組,通常來說需要劃分成三大塊:框架部分、核心業務部分、擴充套件業務部分。 框架部分,通常是用來放通用的工具類方法,還有通用的處理資料、業務的方法,這些方法一般與系統的業務無關。電子商城的後臺系統,通常都會有許可權管理模組,

MySQL提升課程 全面講解MySQL架構設計

太多的 不必要 千萬 難點 之前 執行時間 修改表 cpu 進行 1:並發量:同一時間處理請求數量,同一時間處理請求數量和連接數量是兩個概念,連接數大於處理請求數量2:最好不要在大型活動時候在主庫上進行數據庫備份會占用很大磁盤io3:影響數據庫性能的因素:服務器硬件,磁盤i

讀薄《高效能MySql》(四)查詢效能優化

讀薄《高效能MySql》(四)查詢效能優化 讀薄《高效能MySql》(一)MySql基本知識讀薄《高效能MySql》(二)Scheme與資料優化讀薄《高效能MySql》(三)索引優化讀薄《高效能MySql》(四)查詢效能優化 對 MySql 進行優化,必須對 Scheme,索引,查詢語句一同

MySQL批量SQL插入效能優化

 對於一些資料量較大的系統,資料庫面臨的問題除了查詢效率低下,還有就是資料入庫時間長。特別像報表系統,可能每天花費在資料匯入上的時間就會長達幾個小時之久。因此,優化資料庫插入效能是很有意義的。        網路上的牛人很多,總會有一些手段可以提高insert效率,大家跟我

MySQL提升課程 全面講解MySQL架構設計(扛得住的MySQL資料庫架構)

第1章 例項和故事 決定電商11大促成敗的各個關鍵因素。 1-1 什麼決定了電商雙11大促的成敗 1-2 在雙11大促中的資料庫伺服器 1-3 在大促中什麼影響了資料庫效能 1-4 大表帶來的問題 1-5 大事務帶來的問題 第2章 什麼影響了MySQL效能 詳細

MySQL架構設計——MyISAM儲存引擎與InnoDB儲存引擎

——從MySQL5.1開始,MySQL引入了一個新的概念,外掛式儲存引擎體系結構。可以做到儲存引擎層與SQL層各自更為獨立,耦合更小,最重要的是方便了儲存引擎的載入與移出,可以做到執行時載入新的儲存引

Shuffle過程剖析效能優化

MapReduce確保每個reducer的輸入都按鍵排序。Shuffle:系統執行排序的過程—將map輸出作為輸入傳給reducer(如圖1、圖2)。圖1圖2如圖1、圖2所示,從map輸出到reduce輸入就是shuffle階段。但實際執行過程遠比上圖所示覆雜。Shuffle

centos 6.5 安裝 tomcat8 效能優化_虛擬主機

Tomcat伺服器是一個免費的開放原始碼的Web應用伺服器,屬於輕量級應用伺服器,在中小型系統和併發訪問使用者不是很多的場合下被普遍使用,是開發和除錯JSP程式的首選。 Tomcat和Nginx、Apache(httpd)、lighttpd等Web伺服器一樣,具有處理HTML頁面的功能,另外它還是一個Ser