当前位置: 代码网 > it编程>数据库>Mysql > mysql数据库的分区表示例代码

mysql数据库的分区表示例代码

2024年11月10日 Mysql 我要评论
1.sql表创建下面以时间范围进行创建(每月一个分区,表中创建了四个月的分区)创建:create table test_table ( id int not null auto_increm

1.sql表创建

下面以时间范围进行创建(每月一个分区,表中创建了四个月的分区)

创建:

create table test_table (  
    id int not null auto_increment,  
    content varchar(255),  
    create_time datetime not null,
   primary key (id, create_time) 
) partition by range (to_days(create_time)) (  
    partition p20240601 values less than (to_days('2024-06-01')),  
    partition p20240701 values less than (to_days('2024-07-01')),  
    partition p20241801 values less than (to_days('2024-08-01')),  
    partition p20240901 values less than (to_days('2024-09-01'))
);  

查询分区详情:
select *
from 
    information_schema.partitions 
where 
    table_name = 'test_table';

2、mapper文件

<?xml version="1.0" encoding="utf-8"?>
<!doctype mapper
        public "-//mybatis.org//dtd mapper 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="*.infrastructure.mapper.testtablemapper">

    <resultmap id="testtable" type="*.domain.entity.testtable">
        <id column="id" property="id" typehandler="org.apache.ibatis.type.longtypehandler"/>
        <result property="content" column="content" jdbctype="varchar"/>
        <result property="createtime" column="create_time" jdbctype="timestamp"
                typehandler="org.apache.ibatis.type.localdatetimetypehandler"/>
    </resultmap>

    <!-- 创建新分区 -->
    <update id="createnewpartition">
        alter table test_table
            add partition (  
                partition ${partitionname} values less than (to_days(#{lessthanvalue}))
            )
    </update>

    <!-- 删除旧分区 -->
    <update id="droppartition">
        alter table test_table
        drop
        partition
        ${partitionname}
    </update>

    <!--查询是否存在分区-->
    <select id="exitspartition" resulttype="boolean">
        select count(1) > 0
        from information_schema.partitions
        where table_name = 'test_table'
          and partition_name = #{partitionname}
    </select>

</mapper>

3、service

package *.domain.service;

import *.domain.entity.testtable;
import *.infrastructure.repo.testtablerepository;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.dao.dataaccessexception;
import org.springframework.stereotype.service;

import java.time.localdate;
import java.time.localdatetime;
import java.time.yearmonth;
import java.time.format.datetimeformatter;
import java.util.random;

@service
public class testtableservice {
    @autowired
    testtablerepository repository;

	// 插入数据,如果分区不存在,就创建分区,重新插入
    public void insert() {
        testtable testtable = new testtable();
        testtable.setcontent("test");

        random random = new random();
        int i = math.abs(random.nextint()) % 365;
        localdatetime datetime = localdatetime.now().minusdays(i);
        testtable.setcreatetime(datetime);

        try {
            repository.getbasemapper().insert(testtable);
        } catch (dataaccessexception e) {
            localdate nextmonthfirstday = yearmonth.from(datetime).plusmonths(1).atday(1);
            string lessthanvalue = nextmonthfirstday.format(datetimeformatter.iso_date);
            string partitionname = "p" + lessthanvalue.replaceall("-", "");
            // 创建分区时加锁,如果是多节点,需要分布式锁
            synchronized (this) {
                if (!repository.getbasemapper().exitspartition(partitionname)) {
                    repository.getbasemapper().createnewpartition(partitionname, lessthanvalue);
                }
            }
            repository.getbasemapper().insert(testtable);
        }
    }

	// 创建分区
    public void createnewpartition(string partitionname, string lessthanvalue) {
        repository.getbasemapper().createnewpartition(partitionname, lessthanvalue);
    }

	// 删除分区
    public void droppartition(string partitionname) {
        repository.getbasemapper().droppartition(partitionname);
    }
}

----------------分割线-------------------------------

上述方法用代码来判断分区,新增分区,可能会引入一些奇奇怪怪的问题,因此,优化如下:

【针对mysql,使用mysql的定时事件】

1、首先确认mysql的时间调度器是否已经开启:

-- 查询事件调度器是否开启
show variables like 'event_scheduler'; 

-- 确保事件调度器已经开启  
set global event_scheduler = on;  

2、写存储过程,用于创建新的分区, 这里是按天创建新的分区

delimiter //  
  
create procedure `adddailypartition`()  
begin  
    declare tomorrow date;  
    declare partition_name varchar(20);  
  
    -- 计算明天的日期  
    set tomorrow = date_format(curdate() + interval 1 day, '%y-%m-%d');  
    set partition_name = concat('p', date_format(tomorrow, '%y%m%d'));  
  
    -- 构建alter table语句来添加分区  
    set @sql = concat('alter table test_table ',  
                      'add partition (partition ', partition_name,   
                      ' values less than (to_days(\'', tomorrow, '\')))');  
  
    -- 执行alter table语句  
    prepare stmt from @sql;  
    execute stmt;  
    deallocate prepare stmt;  
end //  
  
delimiter ;  

3、创建定时事件,调用存储过程

-- 创建定时事件  
create event `createdailypartition`  
    on schedule every 1 day starts timestamp(curdate())  
    do call adddailypartition();  

4、查看已经创建的定时事件

select * from information_schema.events; 

在查看事件时,重要的列包括:
event_name: 事件的名称。
event_schema: 事件所属的数据库。
status: 事件的状态,比如是否为enabled或disabled。
starts: 事件开始的时间。
ends: 事件结束的时间(如果有设置的话)。
last_executed: 事件上一次执行的时间。
event_definition: 事件定义,即事件中要执行的sql语句。

总结 

到此这篇关于mysql数据库分区表的文章就介绍到这了,更多相关mysql分区表内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com