如何对zabbix mysql做分区表

MySQL Database Partitioning:
关于zabbix和MySQL分区表 - 支持zabbix 2.0和2.2,mysql在有外键的表不支持分区表。在zabbix 2.0和2.2中history和trend表没有使用外键,因此是可以在这些表中做分区的。

Index changes:
1.如果zabbix的数据库已经有了数据,更改索引可能需要一些时间,根据具体的数据量,需要的时间长短也不一样。
2.在某些版本的MySQL索引的改变会使整个表上读锁。貌似mysql 5.6没有这个限制。
所述第一步骤是修改几个索引以允许做分区,按照下面的命令:
mysql> Alter table history_text drop primary key, add index (id), drop index history_text_2, add index history_text_2 (itemid, id);
Query OK, 0 rows affected (0.49 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> Alter table history_log drop primary key, add index (id), drop index history_log_2, add index history_log_2 (itemid, id);
Query OK, 0 rows affected (2.71 sec)
Records: 0  Duplicates: 0  Warnings: 0

Stored Procedures:
下面开始填写存储过程,需要执行下面的几个存储过程语句,只要能看到"Query OK, 0 rows affected (0.00 sec)"只能就没有什么问题了。
DELIMITER $$
CREATE PROCEDURE `partition_create`(SCHEMANAME VARCHAR(64), TABLENAME VARCHAR(64), PARTITIONNAME VARCHAR(64), CLOCK INT)
BEGIN
        /*
           SCHEMANAME = The DB schema in which to make changes
           TABLENAME = The table with partitions to potentially delete
           PARTITIONNAME = The name of the partition to create
        */
        /*
           Verify that the partition does not already exist
        */
 
        DECLARE RETROWS INT;
        SELECT COUNT(1) INTO RETROWS
        FROM information_schema.partitions
        WHERE table_schema = SCHEMANAME AND TABLE_NAME = TABLENAME AND partition_description >= CLOCK;
 
        IF RETROWS = 0 THEN
                /*
                   1. Print a message indicating that a partition was created.
                   2. Create the SQL to create the partition.
                   3. Execute the SQL from #2.
                */
                SELECT CONCAT( "partition_create(", SCHEMANAME, ",", TABLENAME, ",", PARTITIONNAME, ",", CLOCK, ")" ) AS msg;
                SET @SQL = CONCAT( ‘ALTER TABLE ‘, SCHEMANAME, ‘.‘, TABLENAME, ‘ ADD PARTITION (PARTITION ‘, PARTITIONNAME, ‘ VALUES LESS THAN (‘, CLOCK, ‘));‘ );
                PREPARE STMT FROM @SQL;
                EXECUTE STMT;
                DEALLOCATE PREPARE STMT;
        END IF;
END$$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE `partition_drop`(SCHEMANAME VARCHAR(64), TABLENAME VARCHAR(64), DELETE_BELOW_PARTITION_DATE BIGINT)
BEGIN
        /*
           SCHEMANAME = The DB schema in which to make changes
           TABLENAME = The table with partitions to potentially delete
           DELETE_BELOW_PARTITION_DATE = Delete any partitions with names that are dates older than this one (yyyy-mm-dd)
        */
        DECLARE done INT DEFAULT FALSE;
        DECLARE drop_part_name VARCHAR(16);
 
        /*
           Get a list of all the partitions that are older than the date
           in DELETE_BELOW_PARTITION_DATE.  All partitions are prefixed with
           a "p", so use SUBSTRING TO get rid of that character.
        */
        DECLARE myCursor CURSOR FOR
                SELECT partition_name
                FROM information_schema.partitions
                WHERE table_schema = SCHEMANAME AND TABLE_NAME = TABLENAME AND CAST(SUBSTRING(partition_name FROM 2) AS UNSIGNED) < DELETE_BELOW_PARTITION_DATE;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
 
        /*
           Create the basics for when we need to drop the partition.  Also, create
           @drop_partitions to hold a comma-delimited list of all partitions that
           should be deleted.
        */
        SET @alter_header = CONCAT("ALTER TABLE ", SCHEMANAME, ".", TABLENAME, " DROP PARTITION ");
        SET @drop_partitions = "";
 
        /*
           Start looping through all the partitions that are too old.
        */
        OPEN myCursor;
        read_loop: LOOP
                FETCH myCursor INTO drop_part_name;
                IF done THEN
                        LEAVE read_loop;
                END IF;
                SET @drop_partitions = IF(@drop_partitions = "", drop_part_name, CONCAT(@drop_partitions, ",", drop_part_name));
        END LOOP;
        IF @drop_partitions != "" THEN
                /*
                   1. Build the SQL to drop all the necessary partitions.
                   2. Run the SQL to drop the partitions.
                   3. Print out the table partitions that were deleted.
                */
                SET @full_sql = CONCAT(@alter_header, @drop_partitions, ";");
                PREPARE STMT FROM @full_sql;
                EXECUTE STMT;
                DEALLOCATE PREPARE STMT;
 
                SELECT CONCAT(SCHEMANAME, ".", TABLENAME) AS `table`, @drop_partitions AS `partitions_deleted`;
        ELSE
                /*
                   No partitions are being deleted, so print out "N/A" (Not applicable) to indicate
                   that no changes were made.
                */
                SELECT CONCAT(SCHEMANAME, ".", TABLENAME) AS `table`, "N/A" AS `partitions_deleted`;
        END IF;
END$$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE `partition_maintenance`(SCHEMA_NAME VARCHAR(32), TABLE_NAME VARCHAR(32), KEEP_DATA_DAYS INT, HOURLY_INTERVAL INT, CREATE_NEXT_INTERVALS INT)
BEGIN
        DECLARE OLDER_THAN_PARTITION_DATE VARCHAR(16);
        DECLARE PARTITION_NAME VARCHAR(16);
        DECLARE LESS_THAN_TIMESTAMP INT;
        DECLARE CUR_TIME INT;
 
        CALL partition_verify(SCHEMA_NAME, TABLE_NAME, HOURLY_INTERVAL);
        SET CUR_TIME = UNIX_TIMESTAMP(DATE_FORMAT(NOW(), ‘%Y-%m-%d 00:00:00‘));
 
        SET @__interval = 1;
        create_loop: LOOP
                IF @__interval > CREATE_NEXT_INTERVALS THEN
                        LEAVE create_loop;
                END IF;
 
                SET LESS_THAN_TIMESTAMP = CUR_TIME + (HOURLY_INTERVAL * @__interval * 3600);
                SET PARTITION_NAME = FROM_UNIXTIME(CUR_TIME + HOURLY_INTERVAL * (@__interval - 1) * 3600, ‘p%Y%m%d%H00‘);
                CALL partition_create(SCHEMA_NAME, TABLE_NAME, PARTITION_NAME, LESS_THAN_TIMESTAMP);
                SET @[email protected]__interval+1;
        END LOOP;
 
        SET OLDER_THAN_PARTITION_DATE=DATE_FORMAT(DATE_SUB(NOW(), INTERVAL KEEP_DATA_DAYS DAY), ‘%Y%m%d0000‘);
        CALL partition_drop(SCHEMA_NAME, TABLE_NAME, OLDER_THAN_PARTITION_DATE);
 
END$$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE `partition_verify`(SCHEMANAME VARCHAR(64), TABLENAME VARCHAR(64), HOURLYINTERVAL INT(11))
BEGIN
        DECLARE PARTITION_NAME VARCHAR(16);
        DECLARE RETROWS INT(11);
        DECLARE FUTURE_TIMESTAMP TIMESTAMP;
 
        /*
         * Check if any partitions exist for the given SCHEMANAME.TABLENAME.
         */
        SELECT COUNT(1) INTO RETROWS
        FROM information_schema.partitions
        WHERE table_schema = SCHEMANAME AND TABLE_NAME = TABLENAME AND partition_name IS NULL;
 
        /*
         * If partitions do not exist, go ahead and partition the table
         */
        IF RETROWS = 1 THEN
                /*
                 * Take the current date at 00:00:00 and add HOURLYINTERVAL to it.  This is the timestamp below which we will store values.
                 * We begin partitioning based on the beginning of a day.  This is because we don‘t want to generate a random partition
                 * that won‘t necessarily fall in line with the desired partition naming (ie: if the hour interval is 24 hours, we could
                 * end up creating a partition now named "p201403270600" when all other partitions will be like "p201403280000").
                 */
                SET FUTURE_TIMESTAMP = TIMESTAMPADD(HOUR, HOURLYINTERVAL, CONCAT(CURDATE(), " ", ‘00:00:00‘));
                SET PARTITION_NAME = DATE_FORMAT(CURDATE(), ‘p%Y%m%d%H00‘);
 
                -- Create the partitioning query
                SET @__PARTITION_SQL = CONCAT("ALTER TABLE ", SCHEMANAME, ".", TABLENAME, " PARTITION BY RANGE(`clock`)");
                SET @__PARTITION_SQL = CONCAT(@__PARTITION_SQL, "(PARTITION ", PARTITION_NAME, " VALUES LESS THAN (", UNIX_TIMESTAMP(FUTURE_TIMESTAMP), "));");
 
                -- Run the partitioning query
                PREPARE STMT FROM @__PARTITION_SQL;
                EXECUTE STMT;
                DEALLOCATE PREPARE STMT;
        END IF;
END$$
DELIMITER ;

Using the stored procedures:
存储过程执行完成之后,现在是要如何使用存储过程了,使用类似下面的SQL:
CALL partition_maintenance(‘<zabbix_db_name>‘, ‘<table_name>‘, <days_to_keep_data>, <hourly_interval>, <num_future_intervals_to_create>)
这有几点需要注意:
    1.上面的存储过程使用了变量,所以你需要提供zabbix数据库的库名,表名作为参数。
    2.这个存储过程的变化依赖时间间隔,以小时为时间间隔。
    3.当你使用时,需要明确分区的时间间隔,比如一天一个分区,时间间隔就是24,一个小时一个分区那么时间间隔就是1.
    4.num_future_intervals_to_create是基于hourly_interval。比如你想创建14天的未来的分区来保存数据。如果你设置的时间间隔是24(一天一个分区)那么num_future_intervals_to_create就是14,如果你设置的时间间隔是1(一个小时一个分区)那么num_future_intervals_to_create就是336(24*14).
    5.如果设置的时间间隔是一直变化的,只会影响到新的分区,已经存在的分区不会改变。
        1.如果时间间隔变小,可能得到这样的错误==> "ERROR 1493 (HY000): VALUES LESS THAN value must be strictly increasing for each partition".建议是先删除所有的未来的分区再变更时间间隔。

mysql> CALL partition_maintenance(‘zabbix‘, ‘history‘, 28, 24, 14);
+-----------------------------------------------------------+
| msg                                                       |
+-----------------------------------------------------------+
| partition_create(zabbix,history,p201404160000,1397718000) |
+-----------------------------------------------------------+
1 row in set (0.39 sec)
。。。。
Query OK, 0 rows affected, 1 warning (2.04 sec)

提高调用存储过程:
可以使用下面的存储过程来提高调用:
DELIMITER $$
CREATE PROCEDURE `partition_maintenance_all`(SCHEMA_NAME VARCHAR(32))
BEGIN
                CALL partition_maintenance(SCHEMA_NAME, ‘history‘, 28, 24, 14);
                CALL partition_maintenance(SCHEMA_NAME, ‘history_log‘, 28, 24, 14);
                CALL partition_maintenance(SCHEMA_NAME, ‘history_str‘, 28, 24, 14);
                CALL partition_maintenance(SCHEMA_NAME, ‘history_text‘, 28, 24, 14);
                CALL partition_maintenance(SCHEMA_NAME, ‘history_uint‘, 28, 24, 14);
                CALL partition_maintenance(SCHEMA_NAME, ‘trends‘, 730, 24, 14);
                CALL partition_maintenance(SCHEMA_NAME, ‘trends_uint‘, 730, 24, 14);
END$$
DELIMITER ;

上面的会调用partition_maintenance这个存储过程,history和trends表都是按天进行分区,history保存28天数据,trends表保存730天数据。
调用的话就是这样:
mysql> CALL partition_maintenance_all(‘zabbix‘);
+----------------+--------------------+
| table          | partitions_deleted |
+----------------+--------------------+
| zabbix.history | N/A                |
+----------------+--------------------+
1 row in set (0.01 sec)

....
....
....

+--------------------+--------------------+
| table              | partitions_deleted |
+--------------------+--------------------+
| zabbix.trends_uint | N/A                |
+--------------------+--------------------+
1 row in set (22.85 sec)

Query OK, 0 rows affected, 1 warning (22.85 sec)

Zabbix Housekeeper changes:
使用分区表需要关闭zabbix的history/trends的housekeeper。
Zabbix 2.0.x:
关闭housekeeper需要变更zabbix_server.conf配置文件:DisableHousekeeping=1.关闭了housekeeper,old events, audit entries, and user sessions也无法删除了。
Zabbix 2.2.x:
ZABBIX 2.2引入了更精确的housekeeper。所有的housekeeper配置在zabbix的web端更改,"Administration" -> "General" ,选择"Housekeeping" ,确保history和trends栏的"Enable internal housekeeping"的对勾去掉。

最后:
不要让这些表超时了你设置的提前创建的分区,比如14天,这些表在未来的14天内是没有问题的,但是到第15天就会出错,所以要在14天前提前创建分区表。比如在crontab里面添加一条:
#每天14点30分执行一次
30 14 * * * mysql zabbix -e "CALL partition_maintenance_all(‘zabbix‘);"

此文翻译自:https://www.zabbix.org/wiki/Docs/howto/mysql_partition

时间: 2024-11-08 16:54:27

如何对zabbix mysql做分区表的相关文章

MySQL做练习时总结的一些知识点

MySQL做练习时总结的一些知识点     0:mysql有三种注释方法 上午插入记录的时候一直没有成功,郁闷不知道为什么.因为是很多条记录一起插入,中间一些不用的数据就用"--"来注释了,结果没有效果. 没有办法,在网上找了找,才发现注释符"--"错了,需要一个空格,应该是"-- ". mysql注释符有三种: 1.#... 2."--  ..." 3. mysql 服务器支持 # 到该行结束.-- 到该行结束 以及 的注释

脚本-每3天对数据库目录/var/lib/mysql做物理备份 把数据备份到系统/opt/dbbak目录

每3天对数据库目录/var/lib/mysql做物理备份 把数据备份到系统/opt/dbbak目录 #!/bin/bash DAY=`date+%Y-%m-%d` SIZE=`du-sh /var/lib/mysql` cd/opt/dbbak  2> /dev/null  || mkdir /opt/dbbak echo"Date: $DAY" > /opt/dbbak/dbinfo.txt echo"Total Database Size: $SIZE&quo

使用 Xtrabackup 在线对MySQL做主从复制【转】

1. 说明 1.1 xtrabackup mysqldump对于导出10G以下的数据库或几个表,还是适用的,而且更快捷.一旦数据量达到100-500G,无论是对原库的压力还是导出的性能,mysqldump就力不从心了.Percona-Xtrabackup备份工具,是实现MySQL在线热备工作的不二选择,可进行全量.增量.单表备份和还原.(但当数据量更大时,可能需要考虑分库分表,或使用 LVM 快照来加快备份速度了) 2.2版本 xtrabackup 能对InnoDB和XtraDB存储引擎的数据库

从数据库、代码和服务器对PHP网站Mysql做性能优化

数据库优化是PHP面试几乎都会被问到的事情,也是我们工作中应该注意的事情,当然,如果是小网站无所谓优化不优化,网站访问量大了自然会暴漏数据库的瓶颈,这个瓶颈是各方面问题综合导致的,下面我们来做下数据库优化的总结. 一:对数据库优化 1.创建索引 对于查询占主要的应用来说,索引显得尤为重要.很多时候性能问题很简单的就是因为我们忘了添加索引而造成的,或者说没有添加更为有效的索引导致.如果不加索引的话,那么查找任何哪怕只是一条特定的数据都会进行一次全表扫描,如果一张表的数据量很大而符合条件的结果又很少

Mysql主从(主从不同步解决办法,常见问题及解决办法,在线对mysql做主从复制)

一.主从不同步解决办法 先上Master库: mysql>show processlist; 查看下进程是否Sleep太多.发现很正常. show master status; 也正常. mysql> show master status; +-------------------+----------+--------------+-------------------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore

【MYSQL】 分区表

对于MYSQL的态度一直都是会基本SQL和简单命令就行,最近处理一个数据量很大的项目,为了提高效率,在数据库方面的瓶颈上,选择了使用分区表来提高查询效率.至此和大家一起分享一下. 1.引言 本文初略的讲述了mysql数据库如何分区表. 2.环境要求 在5.1版本中不是默认就安装了,而在之后版本中一般默认选择了安装分区表支持.可以通过如下方式查看当前数据库是否支持分区表操作: 使用show variables like '%partition%';如果不支持分区,那么value字段值为No. 3.

zabbix mysql调优

SELECT table_name AS "Tables", round(((data_length + index_length) / 1024 / 1024), 2) "Size in MB" FROM information_schema.TABLES WHERE table_schema = 'zabbix' ORDER BY (data_length + index_length) DESC limit 10; (查看 mysql数据库表大小) 一 .转换

MySQL的分区表

MySQL从5.1版本开始支持分区的功能.分区是指根据一定的规则,数据库把一个表分解成多个更小的.更容易管理的部分.就访问数据库的应用而言,逻辑上只有一个表或一个索引,但是实际上这个表可能由数十个物理分区对象组成,每个分区都是一个独立的对象,可以独自处理,可以作为表的一部分进行处理.分区对应用来说是完全透明的,不影响应用的业务逻辑. 1.查看使用的MySQL是否支持分区表. 5.6.1版本以后使用show plugins;命令查看 mysql> show plugins; +----------

MYSQL做数据仓库的性能瓶颈

缺少hash join 和parallel 这种工具,MYSQL 注定不是个合适的数据仓库工具. 无论是是myisam还是innodb,在处理一个复杂的SQL查询的时候,并不能发挥多核CPU的性能. 只会有一个CPU正在满负荷地运转. 所以对于一个分析性数据库而言,MYSQL多核实际上是极大的浪费. 但是方案选型了以后,只能做更多的优化. 比如说:手动拆分SQL,再合并结果集. my.cnf配置优化,增加临时表空间和key_buffer_size等等. 即使是KETTLE, DATASTAGE,