MySQL技术内幕(1)

MySQL体系结构和存储引擎

数据库实例

先区分两个名词,数据库和数据库实例:数据库通常指硬盘上数据文件的集合;数据库实例则是管理这些数据文件的进程。

root@ubuntu:/var/lib/mysql# ps -ef | grep mysqld
mysql 956 1 0 09:14 ? 00:00:01 /usr/sbin/mysqld

上面的mysqld就是MySQL的进程,MySQL是单进程多线程的。

MySQL实例启动时读取配置文件my.cnf,根据my.cnf配置进行定制。我们可以在启动mysqld进程时手工指定my.cnf文件位置,默认读取配置文件的顺序为:/etc目录 => /etc/mysql目录 => 当前目录

luth@ubuntu:~$ mysql --help | grep my.cnf
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf

我安装的MySQL的配置文件在/etc/mysql目录下

luth@ubuntu:~$ ls -l /etc/mysql/
total 24
drwxr-xr-x 2 root root 4096 Apr 26 19:57 conf.d
-rw------- 1 root root 317 May 2 13:29 debian.cnf
-rwxr-xr-x 1 root root 120 Jan 19 2017 debian-start
lrwxrwxrwx 1 root root 24 Feb 10 2017 my.cnf -> /etc/alternatives/my.cnf
-rw-r--r-- 1 root root 839 Jul 15 2016 my.cnf.fallback
-rw-r--r-- 1 root root 682 Jul 11 2016 mysql.cnf
drwxr-xr-x 2 root root 4096 May 2 13:29 mysql.conf.d

最后起作用的是mysql.conf.d目录下的mysqld.cnf文件

root@ubuntu:/etc/mysql# ls -l mysql.conf.d/
total 8
-rwxrwxr-x 1 root root 3027 Apr 4 21:31 mysqld.cnf
-rw-r--r-- 1 root root 21 Jul 11 2016 mysqld_safe_syslog.cnf

我们打开mysqld.cnf文件看一下,其中比较重要的有

  • datadir,数据库文件存储的位置
  • port,服务端口
  • bind-address,控制外围访问
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 0.0.0.0

#
# * Fine Tuning
#
key_buffer_size = 16M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover-options = BACKUP
#max_connections = 100
#table_cache = 64
#thread_concurrency = 10
#
# * Query Cache Configuration
#
query_cache_limit = 1M
query_cache_size = 16M
log_error = /var/log/mysql/error.log
expire_logs_days = 10
max_binlog_size = 100M

以上可以看出,数据文件保存在/var/lib/mysql目录。

MySQL体系结构

MySQL数据库区别于其他数据库的最重要的特点是其插件式的表存储引擎,注意:存储引擎是基于表的,不是基于数据库的。

MySQL存储引擎