一、场景分析
在我们使用过程中遇到一张表无法承载数据时,如容量大于2000w-3000w时,就需要用到数据表拆分技术 。下面是实现分表的一种帮助实现类,用于数据表水平拆分。
二、代码示例
package com.juanpi.mkt.utils;
import java.util.zip.CRC32;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 分表帮助类
* @author: 杨杰
*/
public class TableModelHelper {
/**
* 定义记录日志对象
*/
private static Logger logger = LoggerFactory.getLogger(TableModelHelper.class);
/** mod分表 **/
public static String TABLE_SPIT_MOD = "mod";
/** hash分表 **/
public static String TABLE_SPIT_HASH = "hash";
/** crc32分表 **/
public static String TABLE_SPIT_CRC32 = "crc32";
/** mobile分表 **/
public static String TABLE_SPIT_MOBILE = "mobile";
public static int TABLE_NUM = 10;
/**
* 获取表名
*
* @param value
* 值
* @param tableName
* 表名
* @param tableRule
* 分表规则
* @param tablenum
* 表个数
* @return String 分表名
*/
public static String getTableName(String value, String tableName, String tableRule, int tablenum) {
long suffix = 0L;
if (tableRule.equals(TABLE_SPIT_MOD)) {
suffix = Integer.parseInt(value) % 10 + 1;
}
if (tableRule.equals(TABLE_SPIT_HASH)) {
/**Hash算法估计不是这样的**/
suffix = value.hashCode() % (tablenum == 0 ? 10 : tablenum) + 1;
}
if (tableRule.equals(TABLE_SPIT_CRC32)) {
CRC32 crc = new CRC32();
/**将字符串转大写**/
String upperValue = value.toUpperCase();
crc.update(upperValue.getBytes());
suffix = crc.getValue() % (tablenum == 0 ? 10 : tablenum) + 1;
}
if (tableRule.equals(TABLE_SPIT_MOBILE)) {
CRC32 crc = new CRC32();
/**将字符串转大写**/
String upperValue = value.toUpperCase();
crc.update(upperValue.getBytes());
long crcValue = crc.getValue();
long v1 = crcValue % 10;
long v2 = (crcValue % 100)/10;
long v3 = (crcValue % 1000)/100;
long v4 = (crcValue % 10000)/1000;
suffix = (v1 + v2 + v3 + v4)% 10 + 1;
}
logger.info("getTableName "+tableName + "_" + suffix);
return tableName + "_" + suffix;
}
public static String getCouponUserTableName(String tableName,long uid){
long suffix = (uid % 10) + 1;
return tableName + "_" + suffix;
}
public static String getCouponCodeTableName(String value){
long suffix = 0L;
CRC32 crc = new CRC32();
/**将字符串转大写**/
String upperValue = value.toUpperCase();
crc.update(upperValue.getBytes());
long crcValue = crc.getValue();
long v1 = crcValue % 10;
long v2 = (crcValue % 100)/10;
long v3 = (crcValue % 1000)/100;
long v4 = (crcValue % 10000)/1000;
suffix = (v1 + v2 + v3 + v4)% 10 + 1;
return String.valueOf(suffix);
}
/**
* 取得用户分表
*/
public static String getCouponUserTableName(String field) {
String tableName = "js_coupon_user";
tableName = TableModelHelper.getTableName(field, tableName, TableModelHelper.TABLE_SPIT_MOD, TableModelHelper.TABLE_NUM);
return tableName;
}
}