论一种简单高效实现mysql分布式id自增并支持分库分表的方法

论一种简单高效实现mysql分布式id自增并支持分库分表的方法

                                                                                                                     李万鸿-2020-2-28

 

   数据库是IT系统的瓶颈所在,提高数据库性能和存储容量,实现分布式高并发高性能海量数据安全存储使用,是一个非常迫切的现实问题。主键Id是数据库的关键,主键使用数字比使用字符要快很多且省存储空间,Mysql的自增主键非常棒,只要简单加以运用,就可以解决分布式id自增且支持分库分表,巧妙运用mysql自身的事务管理功能,而不用采用其他的软件或方法非常复杂地解决,相比之下,这样效率更高,成本更低,下面详细论述。

一.分布式主键的正确生成

   分布式应用情况下,存在一个用户一次插入多条数据,以提高速度,还存在多个用户对这个数据库进行一或多条数据插入,也即这个数据库的多个连接同时对数据库进行多个insert,如果不做处理,id会错误,这就需要采用一个办法进行解决。

   Mysql的Id自增的原理是插入数据库时,获取LAST_INSERT_ID(),然后生成id,id= LAST_INSERT_ID()+递增值。

 

首先,插入数据库时,需要获取LAST_INSERT_ID()

,并保证数据库的id自增后的id必须实时更新到LAST_INSERT_ID()

,这是保证id顺序递增不错的唯一办法,为此,如下修改inser的sql语句:

 

<insert id="insertStudent" parameterType="com.czd.mybatis01.bean.Student">

    INSERT stu(name)VALUES (#{name})

<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">

 

        SELECT LAST_INSERT_ID()

    </selectKey>

</insert>

这样就保证拿到最新的id进行insert,但id必须实时更新到LAST_INSERT_ID(),这样下一次插入时才会取到正确的id。为此需要在数据库执行:

UPDATE sequence SET id=LAST_INSERT_ID(id+1);
UPDATE 语句会增加顺序计数器并引发向LAST_INSERT_ID() 的下

一次调用,用来返回升级后的值。这样 SELECT 语句会通过

mysql_insert_id()检索这个值,再递增后就可以获取正确的id。

调用LAST_INSERT_ID()产生序列,使用这个函数的效用在于 ID值被保存在服务器中,作为自动产生的值。它适用于多个用户,原因是多个用户均可使用 UPDATE语句并用SELECT语句(或mysql_insert_id()),得到他们自己的序列值,而不会影响其它产生他们自己的序列值的客户端或被其它产生他们自己的序列值的客户端所影响。这样就解决了分布式应用的高并发插入,能正确生成递增id。

注意, mysql_insert_id() 仅会在INSERT 和UPDATE语句后面被升级, 因此你不能在执行了其它诸如SELECT或 SET 这样的SQL语句后使用 C API 函数来找回 LAST_INSERT_ID(expr) 对应的值。

Mysql的int id支持42亿数据,足以满足业务需求,数据量低于1亿基本上就要采取措施,保证数据库的性能。

二、mysql集群的使用

使用上面的方法生成递增数字id,可以轻松实现mysql集群分库分表, 方法如下:

具体实现为:

我们设置获取ID步长为l,一共有n个表分配id。

初始化后,n个表中的id值分别为0,l, 2l,3l…

当应用从任意一个表获取ID,这个表中的ID会在原ID值上增加nl。

举例说明,步长为100,共4个id表

初始化后,4个表中的值分别为, 1:0, 2:100, 3:200, 4:300

假设应用从表2获取了id,那么四个表的值变为,1:0, 2:500, 3:200, 4:300

这样一来有如下几个好处:

实现了全局唯一ID。

不影响业务数据库的扩展。

获取ID有容灾,单个表无法访问不影响全局。如果主从集群,可以解决此问题。

这样写数据库时,不用做任何其他处理,直接写,由于有多台mysql服务器,需要路由选择,实现负载均衡,方法简单:数据库号=Random()%n。

读取时,需要做个简单的id计算,已找到保存这个id的数据库,方法如下:

数据库号=Id%n*l/100

如表2的新插入数据的id=500,500对4*100=400取余=100,100/100=1,即为第二台数据库。然后使用多数据源的办法,选中即可。

这个方法支持mysql线性扩容,直接增加数据库服务器,增加办法很简单,写入一样,记住扩容前的maxID,读取时id计算公式为:

If(id<=maxId){

#n=扩容前的mysql服务器台数

数据库号=Id%n*l/100

}else

{

数据库号=Id%(n+1)*l/100

}

以后再扩容,如法炮制,记住maxId是关键。

这样就可以轻松扩容,增加数据库服务器,支持业务的增长,存储更多的数据。这个办法支持多个主mysql的写,还可以实现主从分离,使用读写分离来提高性能。

 三、mysql集群主从、读写分离

  一主带多从,使用mysql的binlog实现主从同步,多个主mysql之间不复制,充分使用存储,主从同步,保证数据冗余,且便于读写分离,提高性能。应用写数据的方法不变,读数据时需要选择对应主数据库的从数据库地址源,从而使系统性能提升,数据冗余备份,更安全有效。

1.架构图

论一种简单高效实现mysql分布式id自增并支持分库分表的方法转存失败重新上传取消

论一种简单高效实现mysql分布式id自增并支持分库分表的方法

MySQL读写分离是指让master处理写操作,让slave处理读操作,非常适用于读操作量比较大的场景,可减轻master的压力。
使用mysql-proxy实现mysql的读写分离,mysql-proxy实际上是作为后端mysql主从服务器的代理,它直接接受客户端的请求,对SQL语句进行分析,判断出是读操作还是写操作,然后分发至对应的mysql服务器上。

环境准备:

三台主机:
192.168.20.10 master
192.168.20.11 slave
192.168.20.12 proxy

第一:192.168.20.10、11两台mysql搭建主从复制架构。
第二、在proxy机器上安装配置mysql-proxy,实现master/slave架构读写分离。
1、下载mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz
2、安装mysql-proxy
[[email protected] install]# tar zxvf mysql-proxy-0.8.5-linux-el6-x86-64bit.tar.gz
mysql-proxy-0.8.5-linux-el6-x86-64bit/
mysql-proxy-0.8.5-linux-el6-x86-64bit/bin/
......
[[email protected] install]# mv mysql-proxy-0.8.5-linux-el6-x86-64bit /usr/local/
[[email protected] local]# ln -s mysql-proxy-0.8.5-linux-el6-x86-64bit/ mysql-proxy
[[email protected] local]# useradd -r mysql-proxy
[[email protected] local]# id mysql-proxy
uid=493(mysql-proxy) gid=486(mysql-proxy) groups=486(mysql-proxy)

3、添加mysql-proxy自启动
[[email protected] local]# cd /etc/init.d/
[[email protected] init.d]# vi mysql-proxy

!/bin/bash

mysql-proxy This script starts and stops the mysql-proxy daemon

chkconfig: - 78 30

processname: mysql-proxy

description: mysql-proxy is a proxy daemon for mysql

Source function library.

. /etc/rc.d/init.d/functions
prog="/usr/local/mysql-proxy/bin/mysql-proxy"

Source networking configuration.

if [ -f /etc/sysconfig/network ]; then
. /etc/sysconfig/network
fi

Check that networking is up.

[ ${NETWORKING} = "no" ] && exit 0

Set default mysql-proxy configuration.

ADMIN_USER="admin"
ADMIN_PASSWD="admin"
ADMIN_LUA_SCRIPT="/usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua"
PROXY_OPTIONS="--daemon"
PROXY_PID=/var/run/mysql-proxy.pid
PROXY_USER="mysql-proxy"

Source mysql-proxy configuration.

if [ -f /etc/sysconfig/mysql-proxy ]; then
. /etc/sysconfig/mysql-proxy
fi
RETVAL=0
start() {
echo -n prog: "
daemon PROXY_OPTIONS --pid-file= PROXY_ADDRESS" --user= ADMIN_USER" --admin-lua-script=" ADMIN_PASSWORD"
RETVAL= RETVAL -eq 0 ]; then
touch /var/lock/subsys/mysql-proxy
fi
}
stop() {
echo -n prog: "
killproc -p prog
RETVAL= RETVAL -eq 0 ]; then
rm -f /var/lock/subsys/mysql-proxy
rm -f $PROXY_PID
fi
}

See how we were called.

case " PROXY_PIDFILE PROXY_PID 0 {start|stop|restart|reload|status|condrestart|try-restart}"
RETVAL=1
;;
esac
exit $RETVAL

[[email protected] init.d]# chmod +x /etc/init.d/mysql-proxy
[[email protected] init.d]# chkconfig --add mysql-proxy
[[email protected] init.d]# vim /etc/sysconfig/mysql-proxy

Options for mysql-proxy

ADMIN_USER="admin"
ADMIN_PASSWORD="admin"
ADMIN_ADDRESS=""
ADMIN_LUA_SCRIPT="/usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua"
PROXY_ADDRESS=""
PROXY_USER="mysql-proxy"
PROXY_OPTIONS="--daemon --log-level=info --log-use-syslog --plugins=proxy --plugins=admin --proxy-backend-addresses=192.168.20.10:3306 --proxy-read-only-backend-addresses=192.168.20.11:3306 --proxy-lua-script=/usr/local/mysql-proxy/share/doc/mysql-proxy/rw-splitting.lua"

[[email protected] init.d]# vim /usr/local/mysql-proxy/share/doc/mysql-proxy/admin.lua
function set_error(errmsg)
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = errmsg or "error"
}
end
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then
set_error("[admin] we only handle text-based queries (COM_QUERY)")
return proxy.PROXY_SEND_RESULT
end
local query = packet:sub(2)
local rows = { }
local fields = { }
if query:lower() == "select * from backends" then
fields = {
{ name = "backend_ndx",
type = proxy.MYSQL_TYPE_LONG },
{ name = "address",
type = proxy.MYSQL_TYPE_STRING },
{ name = "state",
type = proxy.MYSQL_TYPE_STRING },
{ name = "type",
type = proxy.MYSQL_TYPE_STRING },
{ name = "uuid",
type = proxy.MYSQL_TYPE_STRING },
{ name = "connected_clients",
type = proxy.MYSQL_TYPE_LONG },
}

for i = 1, #proxy.global.backends do
local states = {
"unknown",
"up",
"down"
}
local types = {
"unknown",
"rw",
"ro"
}
local b = proxy.global.backends[i]

rows[#rows + 1] = {
i,
b.dst.name, -- configured backend address
states[b.state + 1], -- the C-id is pushed down starting at 0
types[b.type + 1], -- the C-id is pushed down starting at 0
b.uuid, -- the MySQL Server's UUID if it is managed
b.connected_clients -- currently connected clients
}
end
elseif query:lower() == "select * from help" then
fields = {
{ name = "command",
type = proxy.MYSQL_TYPE_STRING },
{ name = "description",
type = proxy.MYSQL_TYPE_STRING },
}
rows[#rows + 1] = { "SELECT * FROM help", "shows this help" }
rows[#rows + 1] = { "SELECT * FROM backends", "lists the backends and their state" }
else
set_error("use 'SELECT * FROM help' to see the supported commands")
return proxy.PROXY_SEND_RESULT
end

proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
fields = fields,
rows = rows
}
}
return proxy.PROXY_SEND_RESULT
end

4、启动proxy服务:
[[email protected] bin]# service mysql-proxy start
Starting /usr/local/mysql-proxy/bin/mysql-proxy: [ OK ]

[r[email protected] bin]# ss -nalp|grep mysql
LISTEN 0 128 *:4041 : users:(("mysql-proxy",28520,11))
LISTEN 0 128 *:3306 : users:(("mysql-proxy",28520,10))

[[email protected] bin]# mysql -uadmin -padmin -h192.168.20.12 --port=4041
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.99-agent-admin
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT * FROM backends;
+-------------+-----------------+---------+------+------+-------------------+
| backend_ndx | address | state | type | uuid | connected_clients |
+-------------+-----------------+---------+------+------+-------------------+
| 1 | 192.168.20.10:3306 | unknown | rw | NULL | 0 |
| 2 | 192.168.20.11:3306 | unknown | ro | NULL | 0 |
+-------------+-----------------+---------+------+------+-------------------+
2 rows in set (0.00 sec)
配置完成。

第三、测试
[[email protected] ~]# su – mysql
-bash-4.1$ mysql -uroot -p12345
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 5.6.37-log MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql>
mysql> GRANT ALL ON . TO 'alex'@'192.168.20.%' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql>

主从机器上:
tcpdump -i eth0 -nn -XX ip dst 192.168.20.10 and tcp dst port 3306
tcpdump -i eth0 -nn -XX ip dst 192.168.20.11 and tcp dst port 3306
进行抓包观察。

PROXY机器上操作:
[[email protected] bin]# mysql -ualex -p123456 -h192.168.20.12 --port=3306 (这个地方连接3306)
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 26
Server version: 5.6.37-log MySQL Community Server (GPL)
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>create database alex;
mysql>use mysql;
mysql>select * from user \G

[[email protected] ~]# mysql -uadmin -padmin -h192.168.20.12 --port=4041
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.99-agent-admin

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT * FROM backends;
+-------------+-----------------+-------+------+------+-------------------+
| backend_ndx | address | state | type | uuid | connected_clients |
+-------------+-----------------+-------+------+------+-------------------+
| 1 | 192.168.20.10:3306 | up | rw | NULL | 0 |
| 2 | 192.168.20.11:3306 | up | ro | NULL | 0 |
+-------------+-----------------+-------+------+------+-------------------+
2 rows in set (0.00 sec)

成功实现读写分离。

     总之,mysql开源且功能强大,作为业界使用量最广的数据库,采用这个办法简单巧妙地实现了采用自增id对数据库的分布式使用,轻松支持分库分表,线性扩容,还支持读写分离,而方法简单易行,把解决此问题的成本和复杂度降到0,是一个值得使用的好办法,必将为广大IT项目和企业带来益处。