支持MySql的数据库自动分表工具DBShardTools发布

前段时间参与了公司的一个项目,这个项目的特点是数据量、访问量都比较大,考虑使用数据库水平分表策略,Google了大半天,竟然没有找到分表工具。于是自己写了个数据库水平分表工具,支持MS Sql Server和 MySQL,对MYSQL支持比较好。

下面介绍下分表工具的使用方法。

首先是设置数据库连接界面

image

 

输入连接名称(也可以点击右边的选择框,从之前保存的连接中选择),选择数据库类型(目前支持Mysql和Sql Server),输入ip地址、数据库名称、用户名、密码后点击测试连接,如果提示连接成功,说明设置正确。

 

image

 

点击确定按钮进入主界面:

image

 

执行分表操作时,必须要有主表,主表名称可以手工输入也可以通过点击右边的选择框,然后在下拉列表中选择。分表格式可以自己定义,分表逻辑也可以自己定义,后面会具体介绍,例子中的分表逻辑是划分为1000个分表,表名为4位16进制,也就是0000~03e7。操作类型有三种:1、创建分表;2、修改分表(比如说在所有的分表中添加字段或删除字段);3、删除分表。操作类型选择后DDL会自动生成(可以根据需要适当修改)。

image

 

点击确定,执行分表操作。

image

 

查看数据库,分表shoppingcart_0000~shoppingcart_03e7已经生成成功。

 

image

 

自定义分表命名策略

通过实现INameStrategy接口的GetTableNumbers方法来自定义分表后缀名称

public interface INameStrategy
    {
        string[] GetTableNumbers();
    }

比如:

public class NameStrategy : INameStrategy
    {
        private readonly int _startIndex;
        private readonly int _endIndex;
        private readonly int _toBase;
        private readonly int _totalWidth;
        public NameStrategy(int startIndex, int endIndex, int toBase, int totalWidth)
        {
            _startIndex = startIndex;
            _endIndex = endIndex;
            _toBase = toBase;
            _totalWidth = totalWidth;

        }
        public string[] GetTableNumbers()
        {
            List<string> tableNames = new List<string>();
            for (int i = _startIndex; i <= _endIndex; i++)
            {
                tableNames.Add(Convert.ToString(i, _toBase).PadLeft(_totalWidth, '0'));
            }
            return tableNames.ToArray();
        }
    }

 

然后在unity.config中注册自定义的命名策略实现

<register  type="DBShardTools.Core.INameStrategy, DBShardTools.Core" mapTo="DBShardTools.Core.NameStrategy, DBShardTools.Core">
        <constructor>
          <param name="startIndex" value="0" />
          <param name="endIndex" value="999" />
          <param name="toBase" value="16" />
          <param name="totalWidth" value="4" />
        </constructor>
        <lifetime type="singleton"/>
    </register>    

该分表工具目前对MySql支持比较好,比如可以自动生成创建分表的DDL,Sql Server数据库要自己将建表的脚本贴到DDL文本框中。

代码下载

posted @ 2011-10-12 17:46  陈 锋  阅读(9257)  评论(13编辑  收藏  举报