Mysql数据库服务详解

 

  • 数据库介绍
  1. 数据库机器种类

简单的说,数据库(database)就是一个存放数据的仓库,这个仓库是按照一定的数据结构(数据结构是指数据的组织形式或数据之间的联系)来组织、存储的,我们可以通过数据提供的多种方法来管理数据库里的数据。

数据库通常分为层次式数据库、网络式数据库和关系式数据库三种。而不同的数据库是按不同的数据结构来联系和组织的。而在当今的互联网中,最常见的数据库模型主要是两种,即关系型数据库和非关系型数据库

  1. 关系型数据库介绍

关系型数据库模型是把复杂的数据结构归结为简单的二元关系(即二维表格形式)。在关系型数据库中,对数据的操作几乎全部建立在一个或多个关系表格上,通过对这些关联的表格分类、合并、连接或选取等运算来实现数据库的管理

  • 关系型数据库的优点:
  • 容易理解:二维表结构是非常贴近逻辑世界的一个概念,关系模型相对网状、层次等其他模型来说更容易理解
  • 使用方便:通用的SQL语言使得操作关系型数据库非常方便
  • 易于维护:丰富的完整性(实体完整性、参照完整性和用户定义的完整性)大大减低了数据冗余和数据不一致的概率
    • 关系型数据库瓶颈
  • 高并发读写需求:网站的用户并发性非常高,往往达到每秒上万次读写请求,对于传统关系型数据库来说,硬盘I/O是一个很大的瓶颈
  • 海量数据的高效率读写:网站每天产生的数据量是巨大的,对于关系型数据库来说,在一张包含海量数据的表中查询,效率是非常低的
  • 高扩展性和可用性:在基于web的结构当中,数据库是最难进行横向扩展的,当一个应用系统的用户量和访问量与日俱增的时候,数据库却没有办法像web server和app server那样简单的通过添加更多的硬件和服务节点来扩展性能和负载能力。对于很多需要提供24小时不间断服务的网站来说,对数据库系统进行升级和扩展是非常痛苦的事情,往往需要停机维护和数据迁移。
  • 复杂SQL,特别是多表关联查询:在关系型数据库中,导致性能欠佳的最主要原因是多表的关联查询,以及复杂的数据分析类型的复杂SQL报表查询。为了保证数据库的ACID特性,我们必须尽量按照其要求的范式进行设计,关系型数据库中的表都是存储一个格式化的数据结构。每个元组字段的组成都是一样,即使不是每个元组都需要所有的字段,但数据库会为每个元组分配所有的字段,这样的结构可以便于标语表之间进行链接等操作,但从另一个角度来说它也是关系型数据库性能瓶颈的一个因素。
  1. 非关系型数据库介绍

NoSQL,泛指非关系型的数据库。用于指代那些非关系型的,分布式的,且一般不保证遵循ACID原则的数据存储系统。

注:数据库事务必须具备ACID特性,ACID是Atomic原子性,Consistency一致性,Isolation隔离性,Durability持久性。

非关系型数据库提出另一种理念,例如,以键值对存储,且结构不固定,每一个元组可以有不一样的字段,每个元组可以根据需要增加一些自己的键值对,这样就不会局限于固定的结构,可以减少一些时间和空间的开销。使用这种方式,用户可以根据需要去添加自己需要的字段,这样,为了获取用户的不同信息,不需要像关系型数据库中,要对多表进行关联查询。仅需要根据id取出相应的value就可以完成查询。但非关系型数据库由于很少的约束,他也不能够提供像SQL所提供的where这种对于字段属性值情况的查询。并且难以体现设计的完整性。他只适合存储一些较为简单的数据,对于需要进行较复杂查询的数据,SQL数据库显的更为合适

  1. 关系型数据库S.非关系型数据库

关系型数据库的最大特点就是事务的一致性:传统的关系型数据库读写操作都是事务的,具有ACID的特点,这个特性使得关系型数据库可以用于几乎所有对一致性有要求的系统中,如典型的银行系统。

但是,在网页应用中,尤其是SNS应用中,一致性却不是显得那么重要,用户A看到的内容和用户B看到同一用户C内容更新不一致是可以容忍的,或者说,两个人看到同一好友的数据更新的时间差那么几秒是可以容忍的,因此,关系型数据库的最大特点在这里已经无用武之地,起码不是那么重要了。

相反地,关系型数据库为了维护一致性所付出的巨大代价就是其读写性能比较差,而像微博、facebook这类SNS的应用,对并发读写能力要求极高,关系型数据库已经无法应付(在读方面,传统上为了克服关系型数据库缺陷,提高性能,都是增加一级memcache来静态化网页,而在SNS中,变化太快,memchache已经无能为力了),因此,必须用新的一种数据结构存储来代替关系数据库。

关系数据库的另一个特点就是其具有固定的表结构,因此,其扩展性极差,而在SNS中,系统的升级,功能的增加,往往意味着数据结构巨大变动,这一点关系型数据库也难以应付,需要新的结构化数据存储。

于是,非关系型数据库应运而生,由于不可能用一种数据结构化存储应付所有的新的需求,因此,非关系型数据库严格上不是一种数据库,应该是一种数据结构化存储方法的集合。

必须强调的是,数据的持久存储,尤其是海量数据的持久存储,还是需要一种关系数据库这员老将。

  1. 非关系型数据库分类

由于非关系型数据库本身天然的多样性,以及出现的时间较短,因此,不想关系型数据库,有几种数据库能够一统江山,非关系型数据库非常多,并且大部分都是开源的。这些数据库中,其实实现大部分都比较简单,除了一些共性外,很大一部分都是针对某些特定的应用需求出现的,因此,对于该类应用,具有极高的性能。依据结构化方法以及应用场合的不同,主要分为以下几类:

  • 面向高性能并发读写的key-value数据库:

key-value数据库的主要特点即使具有极高的并发读写性能,Redis,Tokyo Cabinet,Flare就是这类的代表

  • 面向海量数据访问的面向文档数据库:

这类数据库的特点是,可以在海量的数据中快速的查询数据,典型代表为MongoDB以及CouchDB

  • 面向可扩展性的分布式数据库:

这类数据库想解决的问题就是传统数据库存在可扩展性上的缺陷,这类数据库可以适应数据量的增加以及数据结构的变化

NOSQL典型产品:Memcached(纯内存)、Redis(持久化缓存)、mongodb

  1. 选择Mysql数据库的原因
  • Mysql性能卓越,服务稳定,很少出现异常宕机
  • Mysql开放源代码且无版权制约,自主性及使用成本低
  • Mysql历史悠久,社区及用户非常活跃,遇到问题,可以寻求帮助
  • Mysql软件体积小,安装使用简单,并且易于维护,安装及维护成本低
  • Mysql品牌口碑效应,使得企业无需考虑就使用,LAMP,LNMP流行架构
  • Mysql支持多种操作系统,提供多种API接口,支持多种语言开发,特变对流行的PHP语言有很好的支持
  1. Mysql数据库分类与版本

MySQL 的官网下载地址:http://www.mysql.com/downloads/

其发布的MySQL版本采用双授权策略,和大多数开源产品的路线一样,分为社区版和商业版,而这两个版本又各自分四个版本依次发布,这四个版本为:Alpha版、Beta版、RC版和GA版

MySQL在发展到5.1系列版本之后,重新规划为三条产品线。

社区版

第一条最正中产品线:根正苗红,4.0-5.0-5.1-5.2,Mysql早期产品的延续系列

第一条产品线:5.4开始–5.7系列。为了更好地整合Mysql,AB公司社区和第三方公司开发的新存储引擎,以及吸收新的实现算法,从而更好地支持SMP架构,提高性能而做了大量的代码重构。主流:互联网公司用Mysql5.5

第一条产品线:6.0–7.1产品系列。为了更好地推广Mysql Cluster版本,以及提高Mysql Cluster的性能和稳定性,以及功能的改进和增加,以及改动Mysql基础功能,使其对Cluster存储引擎提供更有效的支持和优化。

  • MySQL版本选择
  • 6 以后的版本,推荐使用官方版本。
  • Percona:在6版本以后,MySQL将Percon之前优化集成到官方版本中;
  • MariaDB:无INNODB;且核心代码较老
  • MySQL在6以后不断重构源码,安装包越来越大,功能和性能在持续改进
  1. mysql官方网站介绍

官方网站:http://www.mysql.com

  • Developer Zone: MySQL开发工程师板块

Articles: Oracle工程师自己的博客

Plant MySQL: 和MySQL相关从业人员的博客

Bugs:MySQL BugList

Worklog:开发记录

Labs:MySQL实验性项目

  • Downloads:MySQL下载

Enterprise:MySQL企业版本相关,略过

Community:社区版,我们下载和使用社区版

MySQL Community Server:MySQL Server

MySQL Fabric : 和管理相关的工具

MySQL Router:路由中间件

MySQL Utilities:MySQL应用程序包

MySQL Workbench:官方图型化管理界面

MySQL Proxy:MySQL代理。Alpha版本,不推荐

  • 安装Mysql
  1. linux软件的安装方式
  • yum/rpm 简单,快,无法定制
  • 编译安装:复杂,速度慢,可以定制

MySQL5.5以上:./cmake;gmake;gmake install

  • 二进制包:解压就能用(绿色软件,无需安装),简单,快,不好定制

本次选用二进制包:mysql-5.5.32-linux2.6-x86_64.tar.gz

MySQL 的官网下载地址:http://www.mysql.com/downloads/

http://downloads.mysql.com/archives/get/file/mysql-5.5.32-linux2.6-x86_64.tar.gz

  1. MySQL下载
  • 推荐下载Linux-Generic版本
  • Source Code版本主要作用是为了让开发人员研究源码使用,自己编译对性能提升不明显
  • 不推荐Version 5.5.X,有部分bug
  • 推荐使用Version 5.6.X和Version 5.7.X
  1. 二进制包安装mysql-5.5.32

useradd -s /sbin/nologin -M mysql

cd /server/tools

wget http://downloads.mysql.com/archives/get/file/mysql-5.5.32-linux2.6-x86_64.tar.gz

tar zxf mysql-5.5.32-linux2.6-x86_64.tar.gz

mv mysql-5.5.32-linux2.6-x86_64 /application/

ln -s /application/mysql-5.5.32-linux2.6-x86_64 /application/mysql

ls /application/

操作到此步,相当于编译安装到make install

  • 初始化数据库

/application/mysql/scripts/mysql_install_db –basedir=/application/mysql/ –datadir=/application/mysql/data/ –user=mysql

注:/tmp的权限必须为1777(默认)

授权MySQl管理数据库文件

chown -R mysql.mysql /application/mysql

生成mysql配置文件

cp /application/mysql/support-files/my-small.cnf /etc/my.cnf   #默认在/etc下有配置文件

ls /application/mysql/support-files/*.cnf          #以.cnf结尾的都是mysql的配置文件

/application/mysql/support-files/my-huge.cnf

/application/mysql/support-files/my-innodb-heavy-4G.cnf

/application/mysql/support-files/my-large.cnf

/application/mysql/support-files/my-medium.cnf

/application/mysql/support-files/my-small.cnf

注:上面五个配置文件是对应于不同硬件的,虚拟机中一般使用小的配置文件,生产环境配置文件以后会讲解

  • 配置启动mysql脚本

Mysql二进制包启动脚本默认安装路径为/usr/local/mysql,如果置于其他路径应该要修改

sed -i ‘s#/usr/local/mysql#/application/mysql#g’ /application/mysql/bin/mysqld_safe

/application/mysql/bin/mysqld_safe &                   #启动mysql

配置环境变量

echo ‘PATH=”/application/mysql/bin:$PATH”‘>>/etc/profile

source /etc/profile

mysql                  #登录mysql

  • 配置开机自启动脚本

cp /application/mysql/support-files/mysql.server /etc/init.d/mysqld

sed -i ‘s#/usr/local/mysql#/application/mysql#g’ /etc/init.d/mysqld

chmod +x /etc/init.d/mysqld

killall mysqld

/etc/init.d/mysqld start

chkconfig mysqld on

  • 设置mysql密码及更改密码

mysqladmin -uroot password “123456”                 #设置密码

mysqladmin -uroot -p123456 password “0123456”       #修改密码

  • 忘记mysql密码

mysqld_safe –defaults-file=/data/3306/my.cnf –skip-grant-table &  #多实例

mysql -uroot -S /data/3306/mysql.sock

update mysql.user set password=password(‘123456′) where user=’root’ and host=’localhost’;

flush privileges;

  • 安全优化

mysql -uroot -p                 #交互式登录mysql

show databases;

drop database test;             #删除test数据库

select user,host from mysql.user;

drop user ”@’localhost’,”@’nfs-server’,’root’@’::1′;        #删除无用用户

grant all on *.* to ‘root’@localhost identified by ‘123456’ with grant option;flush privileges;        #创建用户

注:如果主机名有大写字母或特殊字符有可能删不了,可以按如下方法删除

delete from mysql.user where user=’root’ and host=’A’;

  • mysql简单命令

help show databases;      #查看帮助

use mysql;                #切换数据库

select user();            #查看当前用户

select database();        #查看当前数据库

select user,host from mysql.user;    #查看当前用户列表

show tables;              #查看当前数据库的所有表

cat /application/mysql/data/nfs-server.err       #查看错误日志

  1. 源码安装mysql-5.1.72
  • 软件下载地址:http://www.mysql.com

useradd -s /sbin/nologin -M mysql

yum install ncurses-devel -y

cd /server/tools/

wget http://downloads.mysql.com/archives/get/file/mysql-5.1.72.tar.gz

tar zxvf mysql-5.1.72.tar.gz

cd mysql-5.1.72

./configure \

–prefix=/application/mysql-5.1.72 \

–with-unix-socket-path=/application/mysql-5.1.72/tmp/mysql.sock \

–localstatedir=/application/mysql-5.1.72/data \

–enable-assembler \

–enable-thread-safe-client \

–with-mysqld-user=mysql \

–with-big-tables \

–without-ndb-debug \

–with-pthread \

–with-extra-charsets=complex \

–with-readline \

–with-ssl \

–with-embedded-server \

–enable-local-infile \

–with-plugins=partition,innobase,innodb_plugin \

–with-mysqld-ldflags=-all-static \

–with-client-ldflags=-all-static

make && make install

ln -s /application/mysql-5.1.72 /application/mysql

  • ./configure出现错误:

checking for termcap functions library… configure: error: No curses/termcap library found

解决:yum install ncurses-devel -y

注意:如果安装LANMP一体化环境,即mysql安装在web服务器上,还需要以下操作,如果不在一台机器上,则mysql至此就安装完成了

  • 初始化数据库

获取mysql配置文件

cd /root/tools/mysql-5.1.72/support-files/

cp my-small.cnf /etc/my.cnf

创建mysql数据库文件

mkdir /application/mysql/data

授权MySQL用户访问mysql安装目录

chown -R mysql.mysql /application/mysql/

初始化数据库

/application/mysql/bin/mysql_install_db –basedir=/application/mysql –datadir=/application/mysql/data –user=mysql

设置mysql开机自启动

cd /root/tool/mysql-5.1.72/support-files/

cp mysql.server /etc/init.d/mysqld

chmod +x /etc/init.d/mysqld

chkconfig –add mysqld

chkconfig mysqld on

启动mysql

/etc/init.d/mysqld start    或者

/application/mysql/bin/mysqld_safe &

停止mysql

法一:mysqladmin shutdown

法二:killall mysqld

添加环境变量

echo ‘export PATH=”$PATH:/application/mysql/bin/”‘>> /etc/profile

source /etc/profile

  1. 源码安装mysql-5.5.48
    • 安装依赖

yum install ncurses-devel libaio-devel -y

  • 安装cmake:cmake官方网站:https://cmake.org/files/

cd /server/tools/

wget https://cmake.org/files/v2.8/cmake-2.8.8.tar.gz

tar zxf cmake-2.8.8.tar.gz

cd cmake-2.8.8

./configure

gmake

gmake install

useradd mysql -s /sbin/nologin -M

  • 安装mysql-5.5.48

cd /server/tools/

wget http://mirrors.sohu.com/mysql/MySQL-5.5/mysql-5.5.48.tar.gz

tar zxvf mysql-5.5.48.tar.gz

cd mysql-5.5.48

cmake . -DCMAKE_INSTALL_PREFIX=/application/mysql-5.5.48 \

-DMYSQL_DATADIR=/application/mysql-5.5.48/data \

-DMYSQL_UNIX_ADDR=/application/mysql-5.5.48/tmp/mysql.sock \

-DDEFAULT_CHARSET=utf8 \

-DDEFAULT_COLLATION=utf8_general_ci \

-DEXTRA_CHARSETS=gbk,gb2312,utf8,ascii \

-DENABLED_LOCAL_INFILE=ON \

-DWITH_INNOBASE_STORAGE_ENGINE=1 \

-DWITH_FEDERATED_STORAGE_ENGINE=1 \

-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \

-DWITHOUT_EXAMPLE_STORAGE_ENGINE=1 \

-DWITHOUT_PARTITION_STORAGE_ENGINE=1 \

-DWITH_FAST_MUTEXES=1 \

-DWITH_ZLIB=bundled \

-DENABLED_LOCAL_INFILE=1 \

-DWITH_READLINE=1 \

-DWITH_EMBEDDED_SERVER=1 \

-DWITH_DEBUG=0

  • 配置结束提示

— Configuring done

— Generating done

— Build files have been written to: /server/tools/mysql-5.5.48

提示,编译时可配置的选项很多,具体可参考结尾附录或官方文档:

make

#[100%] Built target my_safe_process

make install

ln -s /application/mysql-5.5.48/ /application/mysql

如果上述操作未出现错误,则MySQL5.5.48软件cmake方式的安装就算成功

  • 数据库初始化

cd /server/tools/mysql-5.5.48/support-files/

/bin/cp my-small.cnf /etc/my.cnf

chown -R mysql.mysql /application/mysql/

/application/mysql/scripts/mysql_install_db –basedir=/application/mysql –datadir=/application/mysql/data –user=mysql

cd /server/tools/mysql-5.5.48/support-files/

cp mysql.server /etc/init.d/mysqld

chmod +x /etc/init.d/mysqld

chkconfig –add mysqld

chkconfig mysqld on

/etc/init.d/mysqld start

echo ‘export PATH=”$PATH:/application/mysql/bin/”‘>> /etc/profile

source /etc/profile

  1. 源码安装mysql-5.7.22
    • 卸载自带的数据库及boost

rpm -qa | grep mysql

rpm -qa | grep mariadb

rpm -e –nodeps boost-system-1.53.0-25.el7.x86_64

rpm -e –nodeps boost-thread-1.53.0-25.el7.x86_64

rpm -e mariadb-libs-5.5.47-1.el7_2.x86_64

rpm -e –nodeps mariadb-libs-5.5.47-1.el7_2.x86_64

  • 安装依赖及下载软件包

yum -y install make gcc-c++ cmake bison-devel ncurses-devel libaio libaio-devel perl-Data-Dumper net-tools

wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.22.tar.gz

wget http://sourceforge.mirrorservice.org/b/bo/boost/boost/1.59.0/boost_1_59_0.tar.gz

  • 安装mysql

tar zxf boost_1_59_0.tar.gz

mv boost_1_59_0 /usr/local/

tar xvf mysql-5.7.22.tar.gz

cd mysql-5.7.22

cmake \

-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \     #MySQL的安装目录

-DMYSQL_DATADIR=/usr/local/mysql/data \      #MySQL的数据目录

-DSYSCONFDIR=/usr/local/mysql/etc \        #my.cnf路径

-DWITH_MYISAM_STORAGE_ENGINE=1 \          #启用MySQL的myisam引擎

-DWITH_INNOBASE_STORAGE_ENGINE=1 \         #启用MySQL的innobase引擎

-DWITH_MEMORY_STORAGE_ENGINE=1 \                #启用MySQL的memory引擎

-DWITH_READLINE=1 \                             #启用readline库支持(提供可编辑的命令行)

-DMYSQL_UNIX_ADDR=/var/lib/mysql/mysql.sock \   #连接数据库socket路径

-DMYSQL_TCP_PORT=3306 \                         #MySQL端口

-DENABLED_LOCAL_INFILE=1 \                      #允许从本地导入数据

-DWITH_PARTITION_STORAGE_ENGINE=1 \             #安装支持数据库分区

-DEXTRA_CHARSETS=all \                          #安装所有的字符集

-DDEFAULT_CHARSET=utf8 \                        #设置默认字符集为utf-8

-DDEFAULT_COLLATION=utf8_general_ci \           #设定默认排序规则(utf8_general_ci快速/utf8_unicode_ci准确)

-DDOWNLOAD_BOOST=1 \                            #下载boost

-DWITH_BOOST=/usr/local/boost_1_59_0            #boost的安装目录

make && make install

  • 初始化mysql数据库

groupadd mysql

useradd -g mysql -s /sbin/nologin mysql

chown -R mysql:mysql /usr/local/mysql

cd /usr/local/mysql

./bin/mysqld –initialize –user=mysql –datadir=/usr/local/mysql/data/

注:由于5.7版本会初始化设置密码,需要自己修改,跟之前的数据库版本更改方式不一样。

  • 定制mysql配置文件

[root@vm101 ~]# cat /usr/local/mysql/etc/my.cnf

[mysql]

port            = 3308

socket          = /tmp/mysql_3308.sock

default-character-set=utf8

 

[mysqld]

user=mysql

server-id = 1013308

datadir=/usr/local/mysql/data

port            = 3308

socket         = /tmp/mysql_3308.sock

skip-name-resolve

skip-slave-start

default_storage_engine=InnoDB

federated

 

#skip-character-set-client-handshake

character_set_server=utf8

collation_server=utf8_unicode_ci

explicit_defaults_for_timestamp=true

#transaction_isolation = REPEATABLE-READ

 

back_log = 150

max_connections = 3000

max_connect_errors = 10

 

max_allowed_packet = 16M

binlog_cache_size = 1M

max_heap_table_size = 64M

table_open_cache = 2048

thread_cache_size = 8

query_cache_size = 256M

query_cache_limit = 2M

sort_buffer_size = 8M

join_buffer_size = 8M

key_buffer_size = 32M

read_buffer_size = 2M

read_rnd_buffer_size = 16M

bulk_insert_buffer_size = 64M

thread_stack = 192K

tmp_table_size = 64M

 

log-bin=mysql-bin

relay_log=mysql-relay-bin

binlog_format=row

log_slave_updates=1

slow_query_log=1

long_query_time = 1

log_bin_trust_function_creators=1

 

#myisam

#myisam_sort_buffer_size = 16M

#myisam_max_sort_file_size = 16M

#myisam_repair_threads = 1

 

innodb_file_per_table=1

innodb_file_format=barracuda

innodb_strict_mode=1

innodb_buffer_pool_size = 256M

innodb_data_file_path = ibdata1:12M:autoextend

innodb_log_buffer_size = 8M

innodb_log_file_size = 64M

innodb_log_files_in_group = 3

innodb_max_dirty_pages_pct = 90

innodb_flush_method=O_DIRECT

innodb_lock_wait_timeout = 2

innodb_print_all_deadlocks = 1

 

sync_binlog = 1

innodb_flush_log_at_trx_commit = 1

sync_relay_log = 1

sync_master_info = 1

sync_relay_log_info = 1

master-info-repository  = TABLE

relay-log-info-repository = TABLE

 

###auto_increment#####

#auto_increment_increment=2

#auto_increment_offset=2

 

###gtid_mode#######

#gtid-mode=on

#enforce-gtid-consistency=true

 

###rpl_semi_sync#######

#rpl_semi_sync_master_enabled=1

#rpl_semi_sync_master_timeout=1000

#rpl_semi_sync_master_trace_level=32

#rpl_semi_sync_master_wait_no_slave=on

 

[mysqld_safe]

open-files-limit = 8192

注:在启动MySQL服务时,会按照一定次序搜索my.cnf,先在/etc目录下找,找不到则会搜索”$basedir/my.cnf”,然后就是 /usr/local/mysql/my.cnf,这是新版MySQL的配置文件的默认位置!本例中使用自定义配置文件路径/apps/data5.7.16/mysql3308.cnf

注意:在CentOS 6.4版操作系统的最小安装完成后,在/etc目录下会存在一个my.cnf,需要将此文件更名为其他的名字,如:/etc/my.cnf.bak,否则,该文件会干扰源码安装的MySQL的正确配置,造成无法启动。

  • 启动mysql

方式一:

cp support-files/mysql.server /etc/init.d/mysqld

chmod 755 /etc/init.d/mysqld

chkconfig mysqld on

/etc/init.d/mysqld start

方式二:

/usr/local/mysql/bin/mysqld_safe –defaults-file=/usr/local/mysql/etc/my.cnf &

  • 修改密码

/usr/local/mysql/bin/mysql -uroot -p -P3308

Enter password:                                   #输入初始化时生成的密码

mysql> ALTER USER USER() IDENTIFIED BY ‘root-password’;    # MySQL 5.7.6 and up

mysql> SET PASSWORD = PASSWORD(‘root-password’);           # Before MySQL 5.7.6

也可以在my.cnf中加入skip-grant-tables,重启后免密码登录数据库

  1. Linux-Generic版本安装

安装通用步骤:

  • 解压缩mysql-VERSION-linux-glibc2.5-x86_64.tar.gz
  • 打开INSTALL_BINARY 文件,按照shell>开头的步骤进行操作
  • 将export PATH=/安装路径/mysql/bin:$PATH添加到/etc/profile
  • chkconfig mysqld on或者chkconfig mysqld.server on视你的环境而定
    • MySQL 5.6.X 安装:

yum install libaio -y

groupadd mysql

useradd -r -g mysql mysql

cd /usr/local

tar zxvf /path/to/mysql-VERSION-OS.tar.gz

ln -s full-path-to-mysql-VERSION-OS mysql

cd mysql

chown -R mysql .

chgrp -R mysql .

scripts/mysql_install_db –user=mysql

chown -R root .

chown -R mysql data

bin/mysqld_safe –user=mysql &

cp support-files/mysql.server /etc/init.d/mysql.server

  • MySQL 5.7.X 安装

groupadd mysql

useradd -r -g mysql mysql

cd /usr/local

tar zxvf /path/to/mysql-VERSION-OS.tar.gz

ln -s full-path-to-mysql-VERSION-OS mysql

cd mysql

mkdir mysql-files

chmod 770 mysql-files

chown -R mysql .

chgrp -R mysql .

bin/mysqld –initialize –user=mysql #该步骤中会产生临时root@localhost密码,需要自己记录下来

bin/mysql_ssl_rsa_setup

chown -R root .

chown -R mysql data mysql-files

bin/mysqld_safe –user=mysql &

command is optional

cp support-files/mysql.server /etc/init.d/mysql.server

  • 验证安装
  • data目录在安装之前是空目录,安装完成后应该有ibXXX等文件
  • 安装过程中输出的信息中,不应该含有ERROR信息,错误信息默认会写入到$HOSTNAME.err的文件中
  • 通过bin/mysql命令(7.X含有临时密码)可以正常登录
  1. mysql配置文件解析

[root@nfs support-files]# cat my-innodb-heavy-4G.cnf

# The following options will be read by MySQL client applications.

# Note that only client applications shipped by MySQL are guaranteed

# to read this section. If you want your own MySQL client program to

# honor these values, you need to specify it as an option during the

# MySQL client library initialization.

# 下面的选项将被 MySQL 客户端应用程序所读取。注意,只有 MySQL 标准的客户端应用程序是被保证能读取到该章节的。 如果你希望你自己的 MySQL 客户端程序能够承兑这些值,你需要在 MySQL 客户端库初始化中作为一个选项来指定它。

[client]

#password       = [your_password]    # mysql客户端连接mysql时的密码

port            = 3306               #mysql客户端连接时的默认端口

socket          = /application/mysql-5.5.48/tmp/mysql.sock   #与mysql服务器本地通信所使用的socket文件路径

# The MySQL server

[mysqld]

# generic configuration options      # 通用配置选项

port            = 3306               #mysql服务器监听的默认端口

socket          = /application/mysql-5.5.48/tmp/mysql.sock   #socket本地通信文件路径

 

# back_log is the number of connections the operating system can keep in

# the listen queue, before the MySQL connection manager thread has

# processed them. If you have a very high connection rate and experience

# “connection refused” errors, you might need to increase this value.

# Check your OS documentation for the maximum value of this parameter.

# Attempting to set back_log higher than your operating system limit

# will have no effect.

# back_log 是指保持在操作系统监听队列中的连接数量,即在 MySQL 连接管理器线程处理它们之前的连接数量. 如果你有一个非常高的连接率并见到过“拒绝连接”的错误,你可能需要提高该值。

# 检查你的操作系统文档中该参数 的最大值。试图将 back_log 设置得高于你操作系统的限制将不会起到任何作用。

back_log = 50           #back_log 是操作系统在监听队列中所能保持的连接数

 

# Don’t listen on a TCP/IP port at all. This can be a security

# enhancement, if all processes that need to connect to mysqld run

# on the same host.  All interaction with mysqld must be made via Unix

# sockets or named pipes.

# Note that using this option without enabling named pipes on Windows

# (via the “enable-named-pipe” option) will render mysqld useless!

#不用监听一个 TCP/IP 端口。如果运行在相同主机上的所有进程都需要连接到 mysqld,这可能是一个安全增强。所有与 mysqld 的互动都必须通过 Unix sockets(套接字)或命名管道进行。注意,在 Windows 上使用该选项但却不启用命名管道(通过“enable-named-pipe”选项)将使得 mysqld 变得无用。

#skip-networking

 

# The maximum amount of concurrent sessions the MySQL server will

# allow. One of these connections will be reserved for a user with

# SUPER privileges to allow the administrator to login even if the

# connection limit has been reached.

# MySQL 服务器所允许的同时会话数的上限, 其中一个连接将被SUPER权限保留作为管理员登录。即便已经达到了连接数的上限.

max_connections = 100

 

# Maximum amount of errors allowed per host. If this limit is reached,

# the host will be blocked from connecting to the MySQL server until

# “FLUSH HOSTS” has been run or the server was restarted. Invalid

# passwords and other errors during the connect phase result in

# increasing this value. See the “Aborted_connects” status variable for

# global counter.

# 每个主机允许的最大错误数量。 如果已到达该限制,主机将阻止对 MySQL 服务器的连接,直到运行“FLUSH HOSTS”或者服务器被重启。非法的密码以及其他在链接时的错误会增加此值. 查看 “Aborted_connects” 状态来获取全局计数器.

max_connect_errors = 10

 

# The number of open tables for all threads. Increasing this value

# increases the number of file descriptors that mysqld requires.

# Therefore you have to make sure to set the amount of open files

# allowed to at least 4096 in the variable “open-files-limit” in

# section [mysqld_safe]

# 所有线程所打开表的数量。增加此值就增加了mysqld所需要的文件描述符的数量。这样你需要确认在[mysqld_safe]中 “open-files-limit” 变量设置打开文件数量允许至少2048

table_open_cache = 2048

 

# Enable external file level locking. Enabled file locking will have a

# negative impact on performance, so only use it in case you have

# multiple database instances running on the same files (note some

# restrictions still apply!) or if you use other software relying on

# locking MyISAM tables on file level.

# 允许外部文件级别的锁. 打开文件锁会对性能造成负面影响。所以只有在你在同样的文件上运行多个数据库实例时才使用此选项(注意仍会有其他约束!) 或者你在文件层面上使用了其他一些软件依赖来锁定MyISAM表

#external-locking                #默认是没有开启的

 

# The maximum size of a query packet the server can handle as well as

# maximum query size server can process (Important when working with

# large BLOBs).  enlarged dynamically, for each connection.

# 服务所能处理的请求包的最大大小以及服务所能处理的最大的请求大小(当与大的BLOB字段一起工作时相当必要)。每个连接独立的大小.大小动态增加

max_allowed_packet = 16M

 

# The size of the cache to hold the SQL statements for the binary log

# during a transaction. If you often use big, multi-statement

# transactions you can increase this value to get more performance. All

# statements from transactions are buffered in the binary log cache and

# are being written to the binary log at once after the COMMIT.  If the

# transaction is larger than this value, temporary file on disk is used

# instead.  This buffer is allocated per connection on first update

# statement in transaction

# 在一个事务中binlog为了记录SQL状态所持有的cache大小,如果你经常使用大的,多声明的事务,你可以增加此值来获取更大的性能。所有从事务来的状态都将被缓冲在binlog缓冲中然后在提交后一次性写入到binlog中。如果事务比此值大, 会使用磁盘上的临时文件来替代。此缓冲在每个连接的事务第一次更新状态时被创建

binlog_cache_size = 1M

 

# Maximum allowed size for a single HEAP (in memory) table. This option

# is a protection against the accidential creation of a very large HEAP

# table which could otherwise use up all memory resources.

# 独立的内存表所允许的最大容量。此选项为了防止意外创建一个超大的内存表导致耗尽所有的内存资源.

max_heap_table_size = 64M

 

# Size of the buffer used for doing full table scans.

# Allocated per thread, if a full scan is needed.

# MySql读入缓冲区大小。对表进行顺序扫描的请求将分配一个读入缓冲区,MySql会为它分配一段内存缓冲区。read_buffer_size变量控制这一缓冲区的大小。如果对表的顺序扫描请求非常频繁,并且你认为频繁扫描进行得太慢,可以通过增加该变量值以及内存缓冲区大小提高其性能。

read_buffer_size = 2M

 

# When reading rows in sorted order after a sort, the rows are read

# through this buffer to avoid disk seeks. You can improve ORDER BY

# performance a lot, if set this to a high value.

# Allocated per thread, when needed.

# 是MySql的随机读缓冲区大小。当按任意顺序读取行时(例如,按照排序顺序),将分配一个随机读缓存区。进行排序查询时,MySql会首先扫描一遍该缓冲,以避免磁盘搜索,提高查询速度,如果需要排序大量数据,可适当调高该值。但MySql会为每个客户连接发放该缓冲空间,所以应尽量适当设置该值,以避免内存开销过大。

read_rnd_buffer_size = 16M

 

# Sort buffer is used to perform sorts for some ORDER BY and GROUP BY

# queries. If sorted data does not fit into the sort buffer, a disk

# based merge sort is used instead – See the “Sort_merge_passes”

# status variable. Allocated per thread if sort is needed.

# 排序缓冲被用来处理类似ORDER BY以及GROUP BY队列所引起的排序. 如果排序后的数据无法放入排序缓冲, 一个用来替代的基于磁盘的合并分类会被使用. 查看 “Sort_merge_passes” 状态变量, 在排序发生时由每个线程分配

sort_buffer_size = 8M

 

# This buffer is used for the optimization of full JOINs (JOINs without

# indexes). Such JOINs are very bad for performance in most cases

# anyway, but setting this variable to a large value reduces the

# performance impact. See the “Select_full_join” status variable for a

# count of full JOINs. Allocated per thread if full join is found

# 此缓冲被使用来优化全联合(full JOINs 不带索引的联合). 类似的联合在极大多数情况下有非常糟糕的性能表现, 但是将此值设大能够减轻性能影响. 通过 “Select_full_join” 状态变量查看全联合的数量, 当全联合发生时,在每个线程中分配

join_buffer_size = 8M

 

# How many threads we should keep in a cache for reuse. When a client

# disconnects, the client’s threads are put in the cache if there aren’t

# more than thread_cache_size threads from before.  This greatly reduces

# the amount of thread creations needed if you have a lot of new

# connections. (Normally this doesn’t give a notable performance

# improvement if you have a good thread implementation.)

# 我们在cache中保留多少线程用于重用, 当一个客户端断开连接后,如果cache中的线程还少于thread_cache_size, 则客户端线程被放入cache中. 这可以在你需要大量新连接的时候极大的减少线程创建的开销(一般来说如果你有好的线程模型的话,这不会有明显的性能提升.)

thread_cache_size = 8

 

# This permits the application to give the threads system a hint for the

# desired number of threads that should be run at the same time.  This

# value only makes sense on systems that support the thread_concurrency()

# function call (Sun Solaris, for example).

# You should try [number of CPUs]*(2..4) for thread_concurrency

# 此允许应用程序给予线程系统一个提示在同一时间给予渴望被运行的线程的数量. 此值只对于支持 thread_concurrency() 函数的系统有意义( 例如Sun Solaris). 你可可以尝试使用 [CPU数量]*(2..4) 来作为thread_concurrency的值

thread_concurrency = 8

 

# Query cache is used to cache SELECT results and later return them

# without actual executing the same query once again. Having the query

# cache enabled may result in significant speed improvements, if your

# have a lot of identical queries and rarely changing tables. See the

# “Qcache_lowmem_prunes” status variable to check if the current value

# is high enough for your load.

# Note: In case your tables change very often or if your queries are

# textually different every time, the query cache may result in a

# slowdown instead of a performance improvement.

# 查询缓冲常被用来缓冲 SELECT 的结果并且在下一次同样查询的时候不再执行直接返回结果. 打开查询缓冲可以极大的提高服务器速度, 如果你有大量的相同的查询并且很少修改表. 查看 “Qcache_lowmem_prunes” 状态变量来检查是否当前值对于你的负载来说是否足够高. 注意: 在你表经常变化的情况下或者如果你的查询原文每次都不同, 查询缓冲也许引起性能下降而不是性能提升.

query_cache_size = 64M

 

# Only cache result sets that are smaller than this limit. This is to

# protect the query cache of a very large result set overwriting all

# other query results.

# 只有小于此设定值的结果才会被缓冲, 此设置用来保护查询缓冲,防止一个极大的结果集将其他所有的查询结果都覆盖.

query_cache_limit = 2M

 

# Minimum word length to be indexed by the full text search index.

# You might wish to decrease it if you need to search for shorter words.

# Note that you need to rebuild your FULLTEXT index, after you have

# modified this value.

# 被全文检索索引的最小的字长, 你也许希望减少它,如果你需要搜索更短字的时候, 注意在你修改此值之后, 你需要重建你的 FULLTEXT 索引

ft_min_word_len = 4

 

# If your system supports the memlock() function call, you might want to

# enable this option while running MySQL to keep it locked in memory and

# to avoid potential swapping out in case of high memory pressure. Good

# for performance.

# 如果你的系统支持 memlock() 函数,你也许希望打开此选项用以让运行中的mysql在在内存高度紧张的时候,数据在内存中保持锁定并且防止可能被swapping out, 此选项对于性能有益,默认没有开启

#memlock

 

# Table type which is used by default when creating new tables, if not

# specified differently during the CREATE TABLE statement.

# 当创建新表时作为默认使用的表类型, 如果在创建表示没有特别执行表类型,将会使用此值

default-storage-engine = MYISAM

 

# Thread stack size to use. This amount of memory is always reserved at

# connection time. MySQL itself usually needs no more than 64K of

# memory, while if you use your own stack hungry UDF functions or your

# OS requires more stack for some operations, you might need to set this

# to a higher value.

# 线程使用的堆大小. 此容量的内存在每次连接时被预留. MySQL 本身通常不会需要超过64K的内存

如果你使用你自己的需要大量堆的UDF函数, 或者你的操作系统对于某些操作需要更多的堆, 你也许需要将其设置的更高一点.

thread_stack = 192K

 

# Set the default transaction isolation level. Levels available are:

# 设定默认的事务隔离级别.可用的级别如下:

# READ-UNCOMMITTED, READ-COMMITTED, REPEATABLE-READ, SERIALIZABLE

transaction_isolation = REPEATABLE-READ

 

# Maximum size for internal (in-memory) temporary tables. If a table

# grows larger than this value, it is automatically converted to disk

# based table This limitation is for a single table. There can be many of them.

# 内部(内存中)临时表的最大大小, 如果一个表增长到比此值更大,将会自动转换为基于磁盘的表. 此限制是针对单个表的,而不是总和.

tmp_table_size = 64M

 

# Enable binary logging. This is required for acting as a MASTER in a

# replication configuration. You also need the binary log if you need

# the ability to do point in time recovery from your latest backup.

打开二进制日志功能. 在复制(replication)配置中,作为MASTER主服务器必须打开此项, 如果你需要从你最后的备份中做基于时间点的恢复,你也同样需要二进制日志

log-bin=mysql-bin

 

# binary logging format – mixed recommended

# 设定记录二进制日志的格式,有三种格式,基于语句 statement、 基于行 row、 混合方式 mixed

binlog_format=mixed

 

# If you’re using replication with chained slaves (A->B->C), you need to

# enable this option on server B. It enables logging of updates done by

# the slave thread into the slave’s binary log.

# 如果你在使用链式从服务器结构的复制模式 (A->B->C), 你需要在服务器B上打开此项. 此选项打开在从线程上重做过的更新的日志, 并将其写入从服务器的二进制日志.

#log_slave_updates

 

# Enable the full query log. Every query (even ones with incorrect

# syntax) that the server receives will be logged. This is useful for

# debugging, it is usually disabled in production use.

# 打开查询日志. 所有的由服务器接收到的查询 (甚至对于一个错误语法的查询), 都会被记录下来. 这对于调试非常有用, 在生产环境中常常关闭此项, log 默认是没有开启的,会影响服务器性能

#log

 

# Print warnings to the error log file.  If you have any problem with

# MySQL you should enable logging of warnings and examine the error log

# for possible explanations.

# 将警告打印输出到错误log文件. 如果你对于MySQL有任何问题, 你应该打开警告log并且仔细审查错误日志,查出可能的原因. log_warnings 默认没有开启

#log_warnings

 

# Log slow queries. Slow queries are queries which take more than the

# amount of time defined in “long_query_time” or which do not use

# indexes well, if log_short_format is not enabled. It is normally good idea

# to have this turned on if you frequently add new queries to the system.

# 记录慢速查询. 慢速查询是指消耗了比 “long_query_time” 定义的更多时间的查询. 如果 log_long_format 被打开,那些没有使用索引的查询也会被记录. 如果你经常增加新查询到已有的系统内的话.一般来说这是一个好主意

slow_query_log

 

# All queries taking more than this amount of time (in seconds) will be

# trated as slow. Do not use “1” as a value here, as this will result in

# even very fast queries being logged from time to time (as MySQL

# currently measures time with second accuracy only).

# 所有的使用了比这个时间(以秒为单位)更多的查询会被认为是慢速查询. 不要在这里使用1, 否则会导致所有的查询,甚至非常快的查询页被记录下来(由于MySQL 目前时间的精确度只能达到秒的级别).

long_query_time = 2

 

# ***  Replication related settings

 

# Unique server identification number between 1 and 2^32-1. This value

# is required for both master and slave hosts. It defaults to 1 if

# “master-host” is not set, but will MySQL will not function as a master

# if it is omitted.

# 唯一的服务辨识号,数值位于 1 到 2^32-1之间. 此值在master和slave上都需要设置,如果 “master-host” 没有被设置,则默认为1, 但是如果忽略此选项,MySQL不会作为master生效.

server-id = 1

 

# Replication Slave (comment out master section to use this)

#复制的Slave (去掉master段的注释来使其生效)

#

# To configure this host as a replication slave, you can choose between

# two methods :            #为了配置此主机作为复制的slave服务器,你可以选择两种方法:

#

# 1) Use the CHANGE MASTER TO command (fully described in our manual) –

#    the syntax is:       #使用 CHANGE MASTER TO 命令 (在我们的手册中有完整描述) 语法如下:

#

#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,

#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;

#

#    where you replace <host>, <user>, <password> by quoted strings and

#    <port> by the master’s port number (3306 by default).

#你需要替换掉被尖括号包围的字段以及使用master的端口号替换 (默认3306).

#

#    Example:        #例子如下:

#

#    CHANGE MASTER TO MASTER_HOST=’125.564.12.1′, MASTER_PORT=3306,

#    MASTER_USER=’joe’, MASTER_PASSWORD=’secret’;

#

# OR

#

# 2) Set the variables below. However, in case you choose this method, then

#    start replication for the first time (even unsuccessfully, for example

#    if you mistyped the password in master-password and the slave fails to

#    connect), the slave will create a master.info file, and any later

#    changes in this file to the variable values below will be ignored and

#    overridden by the content of the master.info file, unless you shutdown

#    the slave server, delete master.info and restart the slaver server.

#    For that reason, you may want to leave the lines below untouched

#    (commented) and instead use CHANGE MASTER TO (see above)

#设置以下的变量. 不论如何, 在你选择这种方法的情况下, 然后第一次启动复制(甚至不成功的情况下, 例如如果你输入错密码在master-password字段并且slave无法连接), slave会创建一个 master.info 文件,并且之后任何对于包含在此文件内的参数的变化都会被忽略,并且由 master.info 文件内的内容覆盖, 除非你关闭slave服务, 删除 master.info 并且重启slave 服务. 由于这个原因,你也许不想碰一下的配置(注释掉的) 并且使用 CHANGE MASTER TO (查看上面) 来代替

#

# required unique id between 2 and 2^32 – 1

# (and different from the master)

# defaults to 2 if master-host is set

# but will not function as a slave if omitted

#server-id = 2

# 所需要的唯一id号位于 2 和 2^32 – 1之间(并且和master不同)

# 如果master-host被设置了.则默认值是2 , 但是如果省略,则不会生效

#

# The replication master for this slave – required

# 复制结构中的master – 必须

#master-host = <hostname>

#

# The username the slave will use for authentication when connecting to the master-required

# 当连接到master上时slave所用来认证的用户名 – 必须

#master-user = <username>

#

# The password the slave will authenticate with when connecting to the master – required

# 当连接到master上时slave所用来认证的密码 – 必须

#master-password = <password>

#

# The port the master is listening on. optional – defaults to 3306

# master监听的端口. 可选 – 默认是3306

#master-port = <port>

 

# Make the slave read-only. Only users with the SUPER privilege and the

# replication slave thread will be able to modify data on it. You can

# use this to ensure that no applications will accidently modify data on

# the slave instead of the master

# 使得slave只读.只有用户拥有SUPER权限和在上面的slave线程能够修改数据. 你可以使用此项去保证没有应用程序会意外的修改slave而不是master上的数据

#read_only

 

#*** MyISAM Specific options      # MyISAM 相关选项

 

# Size of the Key Buffer, used to cache index blocks for MyISAM tables.

# Do not set it larger than 30% of your available memory, as some memory

# is also required by the OS to cache rows. Even if you’re not using

# MyISAM tables, you should still set it to 8-64M as it will also be

# used for internal temporary disk tables.

# 关键词缓冲的大小, 一般用来缓冲MyISAM表的索引块. 不要将其设置大于你可用内存的30%,因为一部分内存同样被OS用来缓冲行数据, 甚至在你并不使用MyISAM 表的情况下, 你也需要仍旧设置起 8-64M 内存由于它同样会被内部临时磁盘表使用.

key_buffer_size = 32M

 

# MyISAM uses special tree-like cache to make bulk inserts (that is,

# INSERT … SELECT, INSERT … VALUES (…), (…), …, and LOAD DATA

# INFILE) faster. This variable limits the size of the cache tree in

# bytes per thread. Setting it to 0 will disable this optimisation.  Do

# not set it larger than “key_buffer_size” for optimal performance.

# This buffer is allocated when a bulk insert is detected.

# MyISAM 使用特殊的类似树的cache来使得突发插入(这些插入是,INSERT … SELECT, INSERT … VALUES (…), (…), …, 以及 LOAD DATAINFILE) 更快. 此变量限制每个进程中缓冲树的字节数设置为 0 会关闭此优化. 为了最优化不要将此值设置大于 “key_buffer_size”. 当突发插入被检测到时此缓冲将被分配.

bulk_insert_buffer_size = 64M

 

# This buffer is allocated when MySQL needs to rebuild the index in

# REPAIR, OPTIMIZE, ALTER table statements as well as in LOAD DATA INFILE

# into an empty table. It is allocated per thread so be careful with

# large settings.

# 此缓冲当MySQL需要在 REPAIR, OPTIMIZE, ALTER 以及 LOAD DATA INFILE 到一个空表中引起重建索引时被分配. 这在每个线程中被分配.所以在设置大值时需要小心.

myisam_sort_buffer_size = 128M

 

# The maximum size of the temporary file MySQL is allowed to use while

# recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE.

# If the file-size would be bigger than this, the index will be created

# through the key cache (which is slower).

# MySQL重建索引时所允许的最大临时文件的大小 (当 REPAIR, ALTER TABLE 或者 LOAD DATA INFILE). 如果文件大小比此值更大,索引会通过键值缓冲创建(更慢)

myisam_max_sort_file_size = 10G

 

# If a table has more than one index, MyISAM can use more than one

# thread to repair them by sorting in parallel. This makes sense if you

# have multiple CPUs and plenty of memory.

# 如果一个表拥有超过一个索引, MyISAM 可以通过并行排序使用超过一个线程去修复他们. 这对于拥有多个CPU以及大量内存情况的用户,是一个很好的选择.

myisam_repair_threads = 1

 

# Automatically check and repair not properly closed MyISAM tables.

# 自动检查和修复没有适当关闭的 MyISAM 表.

myisam_recover

 

# *** INNODB Specific options ***    # *** INNODB 相关选项 ***

 

# Use this option if you have a MySQL server with InnoDB support enabled

# but you do not plan to use it. This will save memory and disk space

# and speed up some things.

# 如果你的MySQL服务包含InnoDB支持但是并不打算使用的话, 使用此选项会节省内存以及磁盘空间,并且加速某些部分,默认没有开启.

#skip-innodb

 

# Additional memory pool that is used by InnoDB to store metadata

# information.  If InnoDB requires more memory for this purpose it will

# start to allocate it from the OS.  As this is fast enough on most

# recent operating systems, you normally do not need to change this

# value. SHOW INNODB STATUS will display the current amount used.

# 附加的内存池被InnoDB用来保存 metadata 信息, 如果InnoDB为此目的需要更多的内存,它会开始从OS这里申请内存. 由于这个操作在大多数现代操作系统上已经足够快, 你一般不需要修改此值. SHOW INNODB STATUS 命令会显示当先使用的数量.

innodb_additional_mem_pool_size = 16M

 

# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and

# row data. The bigger you set this the less disk I/O is needed to

# access data in tables. On a dedicated database server you may set this

# parameter up to 80% of the machine physical memory size. Do not set it

# too large, though, because competition of the physical memory may

# cause paging in the operating system.  Note that on 32bit systems you

# might be limited to 2-3.5G of user level memory per process, so do not

# set it too high.

# InnoDB使用一个缓冲池来保存索引和原始数据, 不像 MyISAM. 这里你设置越大,你在存取表里面数据时所需要的磁盘I/O越少. 在一个独立使用的数据库服务器上,你可以设置这个变量到服务器物理内存大小的80%,不要设置过大,否则,由于物理内存的竞争可能导致操作系统的内存换页频繁,影响系统性能. 注意在32位系统上你每个进程可能被限制在 2-3.5G 用户层面内存限制, 所以不要设置的太高.

innodb_buffer_pool_size = 2G

 

# InnoDB stores data in one or more data files forming the tablespace.

# If you have a single logical drive for your data, a single

# autoextending file would be good enough. In other cases, a single file

# per device is often a good choice. You can configure InnoDB to use raw

# disk partitions as well – please refer to the manual for more info

# about this.

# InnoDB 将数据保存在一个或者多个数据文件中成为表空间. 如果你只有单个逻辑驱动保存你的数据,一个单个的自增文件就足够好了. 其他情况下.每个设备一个文件一般都是个好的选择. 你也可以配置InnoDB来使用裸盘分区 – 请参考手册来获取更多相关内容

innodb_data_file_path = ibdata1:10M:autoextend

 

# Set this option if you would like the InnoDB tablespace files to be

# stored in another location. By default this is the MySQL datadir.

# 设置此选项如果你希望InnoDB表空间文件被保存在其他分区. 默认保存在MySQL的datadir中.

#innodb_data_home_dir = <directory>

 

# Number of IO threads to use for async IO operations. This value is

# hardcoded to 8 on Unix, but on Windows disk I/O may benefit from a larger number.

# 用来同步IO操作的IO线程的数量. 此值在Unix下被硬编码为8,但是在Windows磁盘I/O可能在一个大数值下表现的更好.

innodb_write_io_threads = 8

innodb_read_io_threads = 8

 

# If you run into InnoDB tablespace corruption, setting this to a nonzero

# value will likely help you to dump your tables. Start from value 1 and

# increase it until you’re able to dump the table successfully.

# 如果你发现InnoDB表空间损坏, 设置此值为一个非零值可能帮助你导出你的表. 1开始并且增加此值直到你能够成功的导出表.

#innodb_force_recovery=1

 

# Number of threads allowed inside the InnoDB kernel. The optimal value

# depends highly on the application, hardware as well as the OS

# scheduler properties. A too high value may lead to thread thrashing.

# 在InnoDB核心内的允许线程数量. 最优值依赖于应用程序,硬件以及操作系统的调度方式. 过高的值可能导致线程的互斥频繁

innodb_thread_concurrency = 16

 

# If set to 1, InnoDB will flush (fsync) the transaction logs to the

# disk at each commit, which offers full ACID behavior. If you are

# willing to compromise this safety, and you are running small

# transactions, you may set this to 0 or 2 to reduce disk I/O to the

# logs. Value 0 means that the log is only written to the log file and

# the log file flushed to disk approximately once per second. Value 2

# means the log is written to the log file at each commit, but the log

# file is only flushed to disk approximately once per second.

# 如果设置为1 ,InnoDB会在每次提交后刷新(fsync)事务日志到磁盘上, 这提供了完整的ACID行为. 如果你愿意对事务安全折衷, 并且你正在运行一个小的事务, 你可以设置此值到0或者2来减少由事务日志引起的磁盘I/O, 值为0意味着该日志只写入到日志文件和日志文件大约每秒一次刷新到磁盘. 值为2意味着每次提交日志将被写入到日志文件,但日志文件只有大约每秒一次刷新到磁盘

innodb_flush_log_at_trx_commit = 1

 

# Speed up InnoDB shutdown. This will disable InnoDB to do a full purge

# and insert buffer merge on shutdown. It may increase shutdown time a

# lot, but InnoDB will have to do it on the next startup instead.

# 加速InnoDB的关闭. 这会阻止InnoDB在关闭时做全清除以及插入缓冲合并. 这可能极大增加关机时间, 但是取而代之的是InnoDB可能在下次启动时做这些操作.

#innodb_fast_shutdown

 

# The size of the buffer InnoDB uses for buffering log data. As soon as

# it is full, InnoDB will have to flush it to disk. As it is flushed

# once per second anyway, it does not make sense to have it very large

# (even with long transactions).

# 用来缓冲日志数据的缓冲区的大小. 当此值快满时, InnoDB将必须刷新数据到磁盘上. 由于基本上每秒都会刷新一次,所以没有必要将此值设置的太大(甚至对于长事务而言)

innodb_log_buffer_size = 8M

 

# Size of each log file in a log group. You should set the combined size

# of log files to about 25%-100% of your buffer pool size to avoid

# unneeded buffer pool flush activity on log file overwrite. However,

# note that a larger logfile size will increase the time needed for the recovery process.

# 在日志组中每个日志文件的大小. 你应该设置日志文件总合大小到你缓冲池大小的25%~100%,来避免在日志文件覆写上不必要的缓冲池刷新行为. 不论如何, 请注意一个大的日志文件大小会增加恢复进程所需要的时间.

innodb_log_file_size = 256M

 

# Total number of files in the log group. A value of 2-3 is usually good enough.

# 在日志组中的文件总数. 通常来说2~3是比较好的.

innodb_log_files_in_group = 3

 

# Location of the InnoDB log files. Default is the MySQL datadir. You may wish to

#point it to a dedicated hard drive or a RAID1 volume for improved performance

# InnoDB的日志文件所在位置. 默认是MySQL的datadir. 你可以将其指定到一个独立的硬盘上或者一个RAID1卷上来提高其性能

#innodb_log_group_home_dir

 

# Maximum allowed percentage of dirty pages in the InnoDB buffer pool.

# If it is reached, InnoDB will start flushing them out agressively to

# not run out of clean pages at all. This is a soft limit, not

# guaranteed to be held.

innodb_max_dirty_pages_pct = 90

# 在InnoDB缓冲池中最大允许的脏页面的比例. 如果达到限额, InnoDB会开始刷新他们防止他们妨碍到干净数据页面. 这是一个软限制,不被保证绝对执行

 

# The flush method InnoDB will use for Log. The tablespace always uses

# doublewrite flush logic. The default value is “fdatasync”, another option is “O_DSYNC”.

# InnoDB用来刷新日志的方法. 表空间总是使用双重写入刷新方法, 默认值是 “fdatasync”,另一个是 “O_DSYNC”.

#innodb_flush_method=O_DSYNC

 

# How long an InnoDB transaction should wait for a lock to be granted

# before being rolled back. InnoDB automatically detects transaction

# deadlocks in its own lock table and rolls back the transaction. If you

# use the LOCK TABLES command, or other transaction-safe storage engines

# than InnoDB in the same transaction, then a deadlock may arise which

# InnoDB cannot notice. In cases like this the timeout is useful to

# resolve the situation.

# 在被回滚前,一个InnoDB的事务应该等待一个锁被批准多久. InnoDB在其拥有的锁表中自动检测事务死锁并且回滚事务. 如果你使用 LOCK TABLES 指令, 或者在同样事务中使用除了InnoDB以外的其他事务安全的存储引擎, 那么一个死锁可能发生而InnoDB无法注意到. 这种情况下这个锁超时值对于解决这种问题就非常有帮助.

innodb_lock_wait_timeout = 120

 

 

[mysqldump]

# Do not buffer the whole result set in memory before writing it to

# file. Required for dumping very large tables quick

# 不要在将内存中的整个结果写入磁盘之前缓存. 在导出非常巨大的表时需要此项

max_allowed_packet = 16M

 

[mysql]

no-auto-rehash

#自动补全表名以及数据库名。默认开启就是禁止了。

 

# Only allow UPDATEs and DELETEs that use keys.

#safe-updates

# 仅仅允许使用键值的 UPDATEs 和 DELETEs .如果没有指定where相关条件,MySQL不会执行相关删除或者清空命令.

[myisamchk]

key_buffer_size = 512M

sort_buffer_size = 512M

read_buffer = 8M

write_buffer = 8M

 

[mysqlhotcopy]

interactive-timeout

 

[mysqld_safe]

# Increase the amount of open files allowed per process. Warning: Make

# sure you have set the global system limit high enough! The high value

# is required for a large number of opened tables

# 增加每个进程的可打开文件数量.

# 警告: 确认你已经将全系统限制设定的足够高!

# 打开大量表需要将此值设大

open-files-limit = 8192

  1. MySQL优化必须调整的10项配置
    • 基本配置

innodb_buffer_pool_size:这是你安装完InnoDB后第一个应该设置的选项。缓冲池是数据和索引缓存的地方:这个值越大越好,这能保证你在大多数的读取操作时使用的是内存而不是硬盘。典型的值是5-6GB(8GB内存),20-25GB(32GB内存),100-120GB(128GB内存)。

innodb_log_file_size:这是redo日志的大小。redo日志被用于确保写操作快速而可靠并且在崩溃时恢复。一直到MySQL 5.1,它都难于调整,因为一方面你想让它更大来提高性能,另一方面你想让它更小来使得崩溃后更快恢复。幸运的是从MySQL 5.5之后,崩溃恢复的性能的到了很大提升,这样你就可以同时拥有较高的写入性能和崩溃恢复性能了。一直到MySQL 5.5,redo日志的总尺寸被限定在4GB(默认可以有2个log文件)。这在MySQL 5.6里被提高。

一开始就把innodb_log_file_size设置成512M(这样有1GB的redo日志)会使你有充裕的写操作空间。如果你知道你的应用程序需要频繁的写入数据并且你使用的时MySQL 5.6,你可以一开始就把它这是成4G。

max_connections:如果你经常看到‘Too many connections’错误,是因为max_connections的值太低了。这非常常见因为应用程序没有正确的关闭数据库连接,你需要比默认的151连接数更大的值。max_connection值被设高了(例如1000或更高)之后一个主要缺陷是当服务器运行1000个或更高的活动事务时会变的没有响应。在应用程序里使用连接池或者在MySQL里使用进程池有助于解决这一问题。

show variables like ‘max_connections’ 查看最大连接数

show  status like ‘max_used_connections’ 查看响应的连接数

max_used_connections / max_connections * 100% (理想值≈ 85%)

back_log  如果MySQL的连接数据达到 max_connections时,新来的请求将会被存在堆栈中,以等待某一连接释放资源,该堆栈的数量即back_log,如果等待连接的数量超过 back_log,将不被授予连接资源。

interactive_timeout    一个交互连接在被服务器在关闭前等待行动的秒数。一个交互的客户被定义为对mysql_real_connect()使用CLIENT_INTERACTIVE 选项的客户。
默认数值是28800,可调优为7200。

  • InnoDB配置

从MySQL 5.5版本开始,InnoDB就是默认的存储引擎并且它比任何其他存储引擎的使用都要多得多。那也是为什么它需要小心配置的原因。

innodb_file_per_table:这项设置告知InnoDB是否需要将所有表的数据和索引存放在共享表空间里(innodb_file_per_table = OFF) 或者为每张表的数据单独放在一个.ibd文件(innodb_file_per_table = ON)。每张表一个文件允许你在drop、truncate或者rebuild表时回收磁盘空间。这对于一些高级特性也是有必要的,比如数据压缩。但是它不会带来任何性能收益。你不想让每张表一个文件的主要场景是:有非常多的表(比如10k+)。

MySQL 5.6中,这个属性默认值是ON,因此大部分情况下你什么都不需要做。对于之前的版本你必需在加载数据之前将这个属性设置为ON,因为它只对新创建的表有影响。

innodb_flush_log_at_trx_commit:主要控制了innodb将log buffer中的数据写入日志文件并flush磁盘的时间点,取值分别为0、1、2三个。0,表示当事务提交时,不做日志写入操作,而是每秒钟将log buffer中的数据写入日志文件并flush磁盘一次;1,则在每秒钟或是每次事物的提交都会引起日志文件写入、flush磁盘的操作,确保了事务的 ACID;设置为2,每次事务提交引起写入日志文件的动作,但每秒钟完成一次flush磁盘操作。 实际测试发现,该值对插入数据的速度影响非常大,设置为2时插入10000条记录只需要2秒,设置为0时只需要1秒,而设置为1时则需要229秒。因此,MySQL手册也建议尽量将插入操作合并成一个事务,这样可以大幅提高速度。根据MySQL手册,在允许丢失最近部分事务的危险的前提下,可以把该值设为0或2。

innodb_flush_method: 这项配置决定了数据和日志写入硬盘的方式。一般来说,如果你有硬件RAID控制器,并且其独立缓存采用write-back机制,并有着电池断电保护,那么应该设置配置为O_DIRECT;否则,大多数情况下应将其设为fdatasync(默认值)。sysbench是一个可以帮助你决定这个选项的好工具。

innodb_log_buffer_size: log缓存大小,一般为1-8M,默认为1M,对于较大的事务,可以增大缓存大小。可设置为4M或8M。这项配置决定了为尚未执行的事务分配的缓存。其默认值(1MB)一般来说已经够用了,但是如果你的事务中包含有二进制大对象或者大文本字段的话,这点缓存很快就会被填满并触发额外的I/O操作。看看Innodb_log_waits状态变量,如果它不是0,增加innodb_log_buffer_size。

innodb_additional_mem_pool_size

该参数指定InnoDB用来存储数据字典和其他内部数据结构的内存池大小。缺省值是1M。通常不用太大,只要够用就行,应该与表结构的复杂度有关系。如果不够用,MySQL会在错误日志中写入一条警告信息。根据MySQL手册,对于2G内存的机器,推荐值是20M,可适当增加。

innodb_thread_concurrency=8

推荐设置为 2*(NumCPUs+NumDisks),默认一般为8

innodb_buffer_pool_size

对于InnoDB表来说,innodb_buffer_pool_size的作用就相当于key_buffer_size对于MyISAM表的作用一样。InnoDB使用该参数指定大小的内存来缓冲数据和索引。对于单独的MySQL数据库服务器,最大可以把该值设置成物理内存的80%。根据MySQL手册,对于2G内存的机器,推荐值是1G(50%)。

  • 缓冲区变量

key_buffer_size

指定索引缓冲区的大小,它决定索引处理的速度,尤其是索引读的速度。通过检查状态值 Key_read_requests和Key_reads,可以知道key_buffer_size设置是否合理。比例key_reads / key_read_requests应该尽可能的低,至少是1:100,1:1000更好(上述状态值可以使用SHOW STATUS LIKE ‘key_read%’获得)。

key_buffer_size只对MyISAM表起作用。即使你不使用MyISAM表,但是内部的临时磁盘表是MyISAM表,也要使用该值。可以使用检查状态值created_tmp_disk_tables得知详情。

举例如下:

mysql> show variables like ‘key_buffer_size‘;

+——————-+————+

| Variable_name | Value      |

+———————+————+

| key_buffer_size | 536870912 |

+———— ———-+————+

key_buffer_size为512MB,我们再看一下key_buffer_size的使用情况:

mysql> show global status like ‘key_read%‘;

+————————+————-+

| Variable_name   | Value    |

+————————+————-+

| Key_read_requests| 27813678764 |

| Key_reads   |  6798830      |

+————————+————-+

一共有27813678764个索引读取请求,有6798830个请求在内存中没有找到直接从硬盘读取索引,计算索引未命中缓存的概率:

key_cache_miss_rate =Key_reads / Key_read_requests * 100%,设置在1/1000左右较好

默认配置数值是8388600(8M),主机有4GB内存,可以调优值为268435456(256MB)。

query_cache_size  

使用查询缓冲,MySQL将查询结果存放在缓冲区中,今后对于同样的SELECT语句(区分大小写),将直接从缓冲区中读取结果。

通过检查状态值Qcache_*,可以知道query_cache_size设置是否合理(上述状态值可以使用SHOW STATUS LIKE ‘Qcache%’获得)。如果Qcache_lowmem_prunes的值非常大,则表明经常出现缓冲不够的情况,如果Qcache_hits的值也 非常大,则表明查询缓冲使用非常频繁,此时需要增加缓冲大小;如果Qcache_hits的值不大,则表明你的查询重复率很低,这种情况下使用查询缓冲反 而会影响效率,那么可以考虑不用查询缓冲。此外,在SELECT语句中加入SQL_NO_CACHE可以明确表示不使用查询缓冲。

query_cache_type指定是否使用查询缓冲,可以设置为0、1、2,该变量是SESSION级的变量。

query_cache_limit指定单个查询能够使用的缓冲区大小,缺省为1M。

query_cache_min_res_unit是在4.1版本以后引入的,它指定分配缓冲区空间的最小单位,缺省为4K。检查状态值 Qcache_free_blocks,如果该值非常大,则表明缓冲区中碎片很多,这就表明查询结果都比较小,此时需要减小 query_cache_min_res_unit。

举例如下:

mysql> show global status like ‘qcache%‘;

+——————————-+—————–+

| Variable_name              | Value      |

+——————————-+—————–+

| Qcache_free_blocks        | 22756      |

| Qcache_free_memory        | 76764704    |

| Qcache_hits                | 213028692   |

| Qcache_inserts             | 208894227   |

| Qcache_lowmem_prunes       | 4010916     |

| Qcache_not_cached         | 13385031    |

| Qcache_queries_in_cache    | 43560      |

| Qcache_total_blocks        | 111212     |

+——————————-+—————–+

mysql> show variables like ‘query_cache%‘;

+————————————–+————–+

| Variable_name            | Value     |

+————————————–+———–+

| query_cache_limit              | 2097152    |

| query_cache_min_res_unit      | 4096       |

| query_cache_size               | 203423744  |

| query_cache_type               | ON        |

| query_cache_wlock_invalidate   | OFF       |

+————————————–+—————+

查询缓存碎片率= Qcache_free_blocks / Qcache_total_blocks * 100%

如果查询缓存碎片率超过20%,可以用FLUSH QUERY CACHE整理缓存碎片,或者试试减小query_cache_min_res_unit,如果你的查询都是小数据量的话。

查询缓存利用率= (query_cache_size – Qcache_free_memory) / query_cache_size * 100%

查询缓存利用率在25%以下的话说明query_cache_size设置的过大,可适当减小;查询缓存利用率在80%以上而且Qcache_lowmem_prunes > 50的话说明query_cache_size可能有点小,要不就是碎片太多。

查询缓存命中率= (Qcache_hits – Qcache_inserts) / Qcache_hits * 100%

示例服务器查询缓存碎片率=20.46%,查询缓存利用率=62.26%,查询缓存命中率=1.94%,命中率很差,可能写操作比较频繁吧,而且可能有些碎片。

record_buffer_size

每个进行一个顺序扫描的线程为其扫描的每张表分配这个大小的一个缓冲区。如果你做很多顺序扫描,你可能想要增加该值。默认数值是131072(128K),可改为16773120 (16M)

read_rnd_buffer_size

随机读缓冲区大小。当按任意顺序读取行时(例如,按照排序顺序),将分配一个随机读缓存区。进行排序查询时,MySQL会首先扫描一遍该缓冲,以避 免磁盘搜索,提高查询速度,如果需要排序大量数据,可适当调高该值。但MySQL会为每个客户连接发放该缓冲空间,所以应尽量适当设置该值,以避免内存开 销过大。 一般可设置为16M

sort_buffer_size

每个需要进行排序的线程分配该大小的一个缓冲区。增加这值加速ORDER BY或GROUP BY操作。默认数值是2097144(2M),可改为16777208 (16M)。

join_buffer_size

联合查询操作所能使用的缓冲区大小

record_buffer_size,read_rnd_buffer_size,sort_buffer_size,join_buffer_size为每个线程独占,也就是说,如果有100个线程连接,则占用为16M*100

table_cache

表高速缓存的大小。每当MySQL访问一个表时,如果在表缓冲区中还有空间,该表就被打开并放入其中,这样可以更快地访问表内容。通过检查峰值时间的状态值Open_tables和Opened_tables,可以决定是否需要增加table_cache的值。如 果你发现open_tables等于table_cache,并且opened_tables在不断增长,那么你就需要增加table_cache的值了 (上述状态值可以使用SHOW STATUS LIKE ‘Open%tables’获得)。注意,不能盲目地把table_cache设置成很大的值。如果设置得太高,可能会造成文件描述符不足,从而造成性能 不稳定或者连接失败。1G内存机器,推荐值是128-256。内存在4GB左右的服务器该参数可设置为256M或384M。

max_heap_table_size

用户可以创建的内存表(memory table)的大小。这个值用来计算内存表的最大行数值。这个变量支持动态改变,即set @max_heap_table_size=# 这个变量和tmp_table_size一起限制了内部内存表的大小。如果某个内部heap(堆积)表大小超过tmp_table_size,MySQL可以根据需要自动将内存中的heap表改为基于硬盘的MyISAM表。

tmp_table_size

通过设置tmp_table_size选项来增加一张临时表的大小,例如做高级GROUP BY操作生成的临时表。如果调高该值,MySQL同时将增加heap表的大小,可达到提高联接查询速度的效果,建议尽量优化查询,要确保查询过程中生成的临时表在内存中,避免临时表过大导致生成基于硬盘的MyISAM表。

mysql> show global status like ‘created_tmp%‘;

+——————————–+———+

| Variable_name          | Value |

+———————————-+———+

| Created_tmp_disk_tables  | 21197   |

| Created_tmp_files        | 58      |

| Created_tmp_tables       | 1771587 |

+——————————–+———–+

每次创建临时表,Created_tmp_tables增加,如果临时表大小超过tmp_table_size,则是在磁盘上创建临时 表,Created_tmp_disk_tables也增加,Created_tmp_files表示MySQL服务创建的临时文件文件数,比较理想的配 置是:

Created_tmp_disk_tables / Created_tmp_tables * 100% <= 25%比如上面的服务器Created_tmp_disk_tables / Created_tmp_tables * 100% =1.20%,应该相当好了

默认为16M,可调到64-256最佳,线程独占,太大可能内存不够I/O堵塞

thread_cache_size

可以复用的保存在缓存中的线程的数量。如果有,新的线程从缓存中取得,当断开连接的时候如果有空间,客户的线程在缓存中。如果有很多新的线程,为了提高性能可以这个变量值。通过比较 Connections和Threads_created状态的变量,可以看到这个变量的作用。默认值为110,可调优为80。

thread_concurrency

推荐设置为服务器 CPU核数的2倍,例如双核的CPU, 那么thread_concurrency的应该为4;2个双核的cpu, thread_concurrency的值应为8。默认为8

wait_timeout

指定一个请求的最大连接时间,对于4GB左右内存的服务器可以设置为5-10。

  • 其他设置

query_cache_size:

uery cache(查询缓存)是一个众所周知的瓶颈,甚至在并发并不多的时候也是如此。 最佳选项是将其从一开始就停用,设置query_cache_size = 0(现在MySQL 5.6的默认值)并利用其他方法加速查询:优化索引、增加拷贝分散负载或者启用额外的缓存(比如memcache或redis)。如果你已经为你的应用启用了query cache并且还没有发现任何问题,query cache可能对你有用。这是如果你想停用它,那就得小心了。

log_bin:

如果你想让数据库服务器充当主节点的备份节点,那么开启二进制日志是必须的。如果这么做了之后,还别忘了设置server_id为一个唯一的值。就算只有一个服务器,如果你想做基于时间点的数据恢复,这(开启二进制日志)也是很有用的:从你最近的备份中恢复(全量备份),并应用二进制日志中的修改(增量备份)。二进制日志一旦创建就将永久保存。所以如果你不想让磁盘空间耗尽,你可以用 PURGE BINARY LOGS 来清除旧文件,或者设置 expire_logs_days 来指定过多少天日志将被自动清除。

记录二进制日志不是没有开销的,所以如果你在一个非主节点的复制节点上不需要它的话,那么建议关闭这个选项。

skip_name_resolve:

当客户端连接数据库服务器时,服务器会进行主机名解析,并且当DNS很慢时,建立连接也会很慢。因此建议在启动服务器时关闭skip_name_resolve选项而不进行DNS查找。唯一的局限是之后GRANT语句中只能使用IP地址了,因此在添加这项设置到一个已有系统中必须格外小心。

  1. mysql配置文件my.cnf
    • 生产配置文件cnf

# line          :V1.9

# mail          :gczheng@139.com

# data          :2018-07-19

# file_name     :my.cnf

# update        :

 

#### 注意     :建议参数根据实际情况作调整

#### 本配置文件主要适用于MySQL 5.7.18版本

 

[client]

port    = 3306

socket  = /data/mysqldata/mysql.sock

#=======================================================================

# # MySQL客户端配置

#=======================================================================

[mysql]

prompt=”(\u@\h) \\R:\\m:\\s [\d]> ”

no-auto-rehash

default-character-set = utf8mb4

#=======================================================================

# MySQL服务器全局配置

#=======================================================================

[mysqld]

user = mysql

port = 3306

server-id = 49180

tmpdir = /data/mysqldata

datadir = /data/mysqldata

socket  = /data/mysqldata/mysql.sock

wait_timeout = 31536000

#interactive_timeout = 600

#sql_mode =                             #sql_mode 配置为空值

#skip_name_resolve = 1

lower_case_table_names = 1

character-set-server = utf8mb4

log_timestamps = SYSTEM

init_connect=’SET NAMES utf8mb4′

max_allowed_packet = 128M

######################### 性能参数 ####################

open_files_limit = 10240

max_connections = 1000

max_user_connections=999

max_connect_errors = 100000

table_open_cache = 1024

thread_cache_size = 64

max_heap_table_size = 32M

query_cache_type = 0

###global cache ###

key_buffer_size = 1G

query_cache_size = 0

tmp_table_size = 32M        #内存临时表

binlog_cache_size = 4M      #二进制日志缓冲

###session cache ###

sort_buffer_size = 8M       #排序缓冲

join_buffer_size = 4M       #表连接缓冲

read_buffer_size = 8M       #顺序读缓冲

read_rnd_buffer_size = 8M   #随机读缓冲

thread_stack = 256KB        #线程的堆栈的大小

######################### binlog设置 #####################

binlog_format = ROW

log_bin = /data/mysqldata/binlog

max_binlog_size = 1G

expire_logs_days = 15       #binlog比较占空间,注意磁盘空间

sync_binlog = 1             #重要参数必须修改为1

######################### 复制设置 ########################

log_slave_updates = 1

#replicate-do-db = test

#binlog-ignore-db = mysql

### GTID 配置 ###

gtid_mode=ON

enforce-gtid-consistency=true

#****************** 开启并行复制(从库)******************

slave-parallel-type=LOGICAL_CLOCK     #基于组提交的并行复制方式

slave-parallel-workers= 8             #并行的SQL线程数量(cpu核数)

master-info_repository=TABLE          #master信息以表的形式保存

relay_log_info_repository=TABLE       #slave信息以表的形式保存

relay_log_recovery=ON                 #relay_log自我修复

######################### innodb ##########################

default_storage_engine = InnoDB

innodb_data_file_path = ibdata1:1G:autoextend

innodb_buffer_pool_size = 1G          #系统内存50%

innodb_open_files = 5120              #调整innodb_open_files设置值,必须小于open_files_limit的设置值

innodb_flush_log_at_trx_commit = 1    #线上服务器必须配置为1

innodb_file_per_table = 1

innodb_lock_wait_timeout = 5

innodb_io_capacity = 400              #根据您的服务器IOPS能力适当调整innodb_io_capacity,配SSD盘可调整到 10000 – 20000

innodb_io_capacity_max = 20000

innodb_flush_method = O_DIRECT

innodb_log_file_size = 1G

innodb_log_files_in_group = 2

innodb_large_prefix = 0

innodb_thread_concurrency = 64

innodb_strict_mode = OFF

innodb_sort_buffer_size = 4194304

#****************** undolog设置 ******************

innodb_undo_directory = /data/undolog            #undolog空间的目录位置

innodb_undo_tablespaces = 2                      #undolog日志文件个数,mysql8之后将弃用

innodb_undo_logs = 128                           #回滚段的数量, 至少大于等于35,默认128。

innodb_max_undo_log_size = 1G                    #当超过这个阀值(默认是1G),会触发truncate回收(收缩)动作,truncate后空间缩小到10M。

innodb_purge_rseg_truncate_frequency = 128       #控制回收(收缩)undolog的频率

innodb_undo_log_truncate = 1                     #即开启在线回收undolog日志文件

######################### log 设置 #####################

log_error = /data/mysqldata/error.log

slow_query_log = 1

long_query_time = 10

slow_query_log_file = /data/mysqldata/slow.log

#=======================================================================

# MySQL mysqldump配置

#=======================================================================

[mysqldump]

quick

max_allowed_packet = 128M

#=======================================================================

# MySQL mysqld_safe配置

#=======================================================================

[mysqld_safe]

log_error = /data/mysqldata/error.log

pid_file = /data/mysqldata/mysqldb.pid

 

[mysqld-5.7]

innodb_buffer_pool_dump_pct = 40

innodb_page_cleaners = 4

innodb_undo_log_truncate = 1

innodb_max_undo_log_size = 2G

innodb_purge_rseg_truncate_frequency = 128

binlog_gtid_simple_recovery=1

log_timestamps=system

transaction_write_set_extraction=MURMUR32

show_compatibility_56=on

  • cnf问题
  • 使用mysqld –help -vv | grep my.cnf查看mysql的配置文件读取顺序
  • 后读取的cnf中的配置,如果有相同项,会覆盖之前的配置
  • 使用–defaults-files可指定配置文件
  1. mysql启动过程
    • MySQL启动

启动mysql服务有三种方式分别是:mysql.sever,mysqld,mysqld_safe。

  • mysqld_safe –user=mysql & 即可启动,mysqld_safe是一个守护mysqld进程的脚本程序,旨在mysqld意外停止时,可以重启mysqld进程
  • 也可以通过INSTALL_BINARRY中的的步骤,使用/etc/init.d/mysql.server start进行启动(启动脚本以你复制的实际名字为准,通常改名为mysqld,即/etc/init.d/mysqld start)
  • mysqld启动。直接运行mysqld程序也是可以启动mysql服务,mysqld会使用默认的配置进行启动,对于多实例的mysql使用这种方法就不好实现。
    • server启动

默认的mysql的服务启动程序是mysql.server,mysql.server程序主要是会用到两个程序和一个函数,分别是my_print_defaults、myslqd_safe和parse_server_arguments

  • my_print_defaults:读取cnf配置文件,输出参数传递给parse_server_arguments,该程序只读my.cnf中[mysqld]中的参数。
  • parse_server_arguments该函数处理my_print_defaults传递过来的参数赋值给–basedir、–datadir、–pid-file、–server-startup-timeout
  • myslqd_safe:mysqld_safe程序调用mysqld程序来启动mysql服务

查看mysql.mysql

[root@lnmp support-files]# cat -n mysql.server

124 parse_server_arguments() {

125   for arg do

126     case “$arg” in

127       –basedir=*)  basedir=`echo “$arg” | sed -e ‘s/^[^=]*=//’`

128                     bindir=”$basedir/bin”

129                     if test -z “$datadir_set”; then

130                       datadir=”$basedir/data”

131                     fi

132                     sbindir=”$basedir/sbin”

133                     libexecdir=”$basedir/libexec”

134         ;;

135       –datadir=*)  datadir=`echo “$arg” | sed -e ‘s/^[^=]*=//’`

136                     datadir_set=1

137         ;;

138       –pid-file=*) mysqld_pid_file_path=`echo “$arg” | sed -e ‘s/^[^=]*=//’` ;;

139       –service-startup-timeout=*) service_startup_timeout=`echo “$arg” | sed -e ‘s/^[^=]*=//’` ;;

140     esac

141   done

142 }

……

279      if test -x $bindir/mysqld_safe

283        $bindir/mysqld_safe –datadir=”$datadir” –pid-file=”$mysqld_pid_file_path” $other_args >/dev/null 2>&1 &

294        log_failure_msg “Couldn’t find MySQL server ($bindir/mysqld_safe)”

查看mysql进程

[root@lnmp support-files]# ps -ef|grep mysql

root       1056      1  0 21:52 ?        00:00:00 /bin/sh /home/mysql/mysql/bin/mysqld_safe –datadir=/home/mysql/mysql/data –pid-file=/home/mysql/mysql/data/lnmp.pid

mysql      1211   1056  0 21:52 ?        00:00:50 /home/mysql/mysql/bin/mysqld –basedir=/home/mysql/mysql –datadir=/home/mysql/mysql/data –plugin-dir=/home/mysql/mysql/lib/plugin –user=mysql –log-error=/home/mysql/mysql/data/lnmp.err –pid-file=/home/mysql/mysql/data/lnmp.pid

root       1562   1354  0 23:41 pts/0    00:00:00 grep mysql

查看mysql进程信息可以看到通过mysql.server启动首先会对参数–datedir和–pid-file赋值,这两个参数是从my.cnf文件[mysqld]部分中读取来的,而且这两个参数的值不会受到mysqld_safe程序中的参数赋值给覆盖。但是在my.cnf中其它的参数值如果[mysqld]和[mysqld_safe]相同的话就以mysqld_safe为主

  • mysqld_safe启动

在以前老的版本mysqld_safe是主要的启动方式,而且参数也非常多;对于多实例的服务器需要用到mysqld_safe来启动。mysqld_safe会调用mysqld程序启动mysql服务,并且mysqld_safe会读取my.cnf中的配置参数值来启动mysql服务。mysqld_safe本身也有一些启动参数并且这些启动参数优先于配置文件中相应的参数。

[root@lnmp ~]# mysqld_safe –help

–no-defaults                     不读任何选项文件

–defaults-file=FILE  配置自定义的默认文件,如果是多实例的服务器这里就需要配置成对应的my.cnf

–defaults-extra-file=FILE    除了默认文件之外所读取的选项文件名

–ledir=DIRECTORY :  指定mysqld文件所在的路径,对于多实例的服务器可以用来分别指定实例的位置。

–open-files-limit=LIMIT      能打开的最大文件数量

–core-file-size=LIMIT     mysqld能够创建的内核文件的大小。选项值传递给ulimit -c

–timezone=TZ :      为给定的选项值设置TZ时区环境变量。从操作系统文档查阅合法的时区规定格式

–malloc-lib=LIB     预加载共享库lib

–mysqld=FILE      想要启动的服务器程序名(在ledir目录)。默认是mysqld也可以是其它的名称。

–mysqld-version=VERSION       如果你使用–mysqld-version =max,mysqld_safe启动ledir目录中的mysqld-max程序。如果–mysqld-version的参数为空,mysqld_safe使用目录中的mysqld。

–nice=NICE           使用nice程序根据给定值来设置mysqld的调度优先级。

–plugin-dir=DIR      配置mysql服务的plugin路径,/usr/local/mysql/lib/plugin

–skip-kill-mysqld                Don’t try to kill stray mysqld processes

–syslog                          Log messages to syslog with ‘logger’

–skip-syslog                     Log messages to error log (default)

–syslog-tag=TAG                  Pass -t “mysqld-TAG” to ‘logger’

通过mysqld_safe启动

[root@lnmp ~]# /home/mysql/mysql/bin/mysqld_safe &

[1] 1661

[root@lnmp ~]# 170505 15:56:40 mysqld_safe Logging to ‘/home/mysql/mysql/data/lnmp.err’.

170505 15:56:40 mysqld_safe Starting mysqld daemon with databases from /home/mysql/mysql/data

  • 总结

在现在的新版本中不建议在[mysqld_safe]中进行参数的配置,对应多实例的服务器在启动的时候可以通过mysqld_safe来指定不同实例的路径和配置文件进行启动,需要用到—-defaults-file、–ledir两个参数进行启动,从启动的代码可以看出mysql的启动要用到的两个关键参数–datadir –pid-file,所以为什么经常会在启动和关闭mysql的时候提示找不到pid了。

  1. MySQL升级
    • 环境说明

般说来,MySQL数据库的二进制数据文件,也就是my.cnf中的配置项datadir所在的位置,和我们MySQL应用程序安装的位置是需要分开的,仅仅通过配置项告诉MySQL,数据库的数据存在datadir这个目录下。当程序和数据分离以后,方便我们对数据库应用程序做版本的升级或者回退。

  • 环境举例

MySQL安装目录:

  • MySQL 5.6.27: /usr/local/mysql-5.6.27-linux-glibc2.5-x86_64
  • MySQL 5.7.18 : /usr/local/mysql-5.7.18-linux-glibc2.5-x86_64

datadir目录:

  • /data/mysqdata/

初始环境:

[root@node2 ~]# ll /usr/local/

lrwxrwxrwx  1 root root  34 Nov 16 11:30 mysql -> mysql-5.6.27-linux-glibc2.5-x86_64

lrwxrwxrwx  1 root root  46 Nov 22 22:56 mysql-5.6.27-linux-glibc2.5-x86_64

drwxr-xr-x  9 root root 120 Nov 22 22:54 mysql-5.7.18-linux-glibc2.5-x86_64

[root@node2 ~]# ll /data/mysqldata/

— 1 mysql mysql  259234780 11月 22 11:40 binlog.000269

-rw-r—– 1 mysql mysql       1007 11月 19 13:06 binlog.index

-rw-r—– 1 mysql mysql    2274867 11月 22 14:53 error.log

-rw-r—– 1 mysql mysql    4676173 11月 19 10:57 ib_buffer_pool

-rw-r—– 1 mysql mysql 3087007744 11月 22 14:12 ibdata1

-rw-r—– 1 mysql mysql 2147483648 11月 22 14:12 ib_logfile0

-rw-r—– 1 mysql mysql 2147483648 11月 22 14:12 ib_logfile1

-rw-r—– 1 mysql mysql   12582912 11月 22 16:11 ibtmp1

drwxr-x— 2 mysql mysql       4096 11月 14 17:59 mysql

-rw-r—– 1 mysql mysql          6 11月 19 12:29 mysqldb.pid

srwxrwxrwx 1 mysql mysql          0 11月 19 12:29 mysql.sock

-rw——- 1 mysql mysql          6 11月 19 12:29 mysql.sock.lock

drwxr-x— 2 mysql mysql       4096 11月 14 17:59 performance_schema

drwxr-x— 2 mysql mysql       4096 11月 19 13:19 sbtest

-rw-r—– 1 mysql mysql 5930475516 11月 19 13:07 slow.log

drwxr-x— 2 mysql mysql      12288 11月 14 17:59 sys

drwxr-x— 2 mysql mysql       4096 11月 17 08:58 sysbench

  • 版本升级

/etc/init.d/mysqld stop  #安全的停止数据库的运行

cd /usr/local/

unlink mysql

ln -s mysql-5.7.18-linux-glibc2.5-x86_64 mysql     #此时,MySQL的应用程序版本已经升级完成

cd /usr/local/mysql

chown root.mysql . -R

cp -r /data/mysql_data/mysql /备份路径/mysql_5_6_27.backup    #该步骤将mysql5.6.27版本的系统表进行了备份,以便将来可以回退

/etc/init.d/mysqld start       #且可以使用 mysql -u root -p (原密码) 进入数据库, 存在test表,而没有sys表(数据的二进制文件兼容), 但是如果去看error.log会发现好多的WARNNING, 所以,这个时候我们要去 upgrade 去升级

mysql_upgrade -p -s            #参数 -s 一定要加,表示只更新系统表,-s: upgrade-system-tables

#如果不加-s,则会把所有库的表以5.7.18的方式重建,线上千万别这样操作,因为数据库二进制文件是兼容的,无需升级,什么时候不需要-s, 当一些老的版本的存储格式需要新的特性,来提升性能时,不加-s,即使通过slave进行升级,也推荐使用该方式升级,速度比较快

[root@node2 ~]# mysql -u root -p

mysql> show databases;

+——————–+

| Database           |

+——————–+

| information_schema |

| mysql              |  # 这个就是升级后的系统库,如果回退,将备份的拷贝回来覆盖即可

| performance_schema |

| sys                |  # 5.7 新的sys库

| test               |  # 5.6 中的test库

+——————–+

5 rows in set (0.00 sec)

注意:MySQL5.1.X、5.5.X 、5.6.X 是可以直接通过该方式升级到5.7.X。但是5.0.X未知,需要测试, 如果原来datadir是/data/mysqldata,要确保my.cnf中的数据位置和升级前后的实际数据位置是一致的。

  • 关于降级问题的说明

通过覆盖mysql系统表的方式存在问题,会导致启动不起来。

  • MySQL备份
  1. mysql备份简介
    • 逻辑备份:

mysqldump备份工具小于50G的数据量

原理:将数据库的数据以逻辑的SQL语句的方式导出

  • 物理备份:

scp /application/mysql/data/ 拷贝到独立数据库上就可以

xtrabackup开源的物理备份工具

  1. 备份mysql
    • 全库备份

mysqldump -uroot -p123456 -B -A -x –events|gzip >/opt/bak_$(date +%F).sql.gz

-A :备份所有库

-B :备份多个库,并添加use 库名;create database 库名 等的功能

-x :锁表。会影响读写,尽量晚上执行

|gzip:压缩率高,传输快

.sql.gz:表示SQl语句数据,.gz是压缩包

  • 单库备份

mysqldump -uroot -p123456 -B -x wordpress|gzip >/opt/bak_wordpress_$(date +%F).sql.gz

注意:备份操作都在命令行操作,不需要登录数据库。同理也可以将数据库定时打包备份到备份服务器

  • 多表备份

mysqldump -P5858 -h127.0.0.1 -uroot athena $(mysql -P5858 -h127.0.0.1 -uroot -D athena -Bs -e “show tables like ‘athena%’;”) >./athena_athena.sql

  • mysql数据恢复
  1. 迁移数据库

scp -rp -P52113 bak_2016-03-12.sql.gz root@192.168.80.101:/opt

root@192.168.80.101’s password:

Permission denied, please try again.           #迁移数据文件失败

scp -rp -P52113 /opt/bak_wordpress_2016-03-12.sql.gz liwen@192.168.80.101:/tmp

liwen@192.168.80.101’s password:

bak_wordpress_2016-03-12.sql.gz              100%  127KB 126.6KB/s   00:00  #迁移成功

注意:如果/etc/ssh/sshd_config文件中 PermitRootLogin no是不能使用root用户远程拷贝过去的

  1. 数据恢复

cd /tmp/

gzip -d bak_wordpress_2016-03-12.sql.gz

mysql -uroot -p123456 <bak_wordpress_2016-03-12.sql

mysql -uroot -p123456

grant select,insert,update,delete on wordpress.* to wordpress@’192.168.80.%’ identified by ‘123456’;

  1. 整合LNMP

web服务器操作:

/etc/init.d/mysqld stop                                 #停止本地数据库

cd /application/nginx/html/blog/

vi wp-config.php

仅仅修改define(‘DB_HOST’, ‘192.168.80.101’); 最好修改为域名并做解析

 

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇