java序列生成器_求助大神,要求用java代码写一个序列生成器

展开全部

import java.util.HashMap;

import java.security.KeyException;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

/**

* 类Key是一个数据库主键生成器,用序列号的方式来产生数据库中需要的主键值。

Key目前62616964757a686964616fe78988e69d8331333363353838支持的数据库包括Oracle的所有版本、MySql的3.x以上的版本

* 以及所有支持max()函数的数据库,支持字段类型仅为数字类型的主键,对于字符及其它类型的主键尚不提供支持。

* 在使用时只需提供表名、字段名(主键)以及到数据库的JDBC连接,如果想要获得message表的id字段的下一个 主键值时:

*

 
  

*     java.sql.Connection conn = ...;

*     org.shaoye.common.sql.Key key = org.shaoye.common.sql.Key.getInstance();

*     int keyValue = key.getNextKey("message", "id", conn);

*     String sql = "insert into message (id,...) values (" + keyValue + ",...)";

*     //执行插入操作...

*

*

* @author 令少爷(shaoye@vip.sina.com)

* @since magic 0.1

*/

public final class Key {

/**

* key的最大值,默认为9223372036854775807,即long类型的最大值

*/

private long max = 9223372036854775807L;

/**

* key的最小值,默认为1

* */

private long min = 1L;

/**

* Key的唯一实例,通过getInstance()方法获得

* */

private static Key keygen = new Key();

/**

* KeyInfo类的实例列表,默认容量为5个

* */

private HashMap keyList = new HashMap(5); // keyInfo

// 列表

/**

* 私有的默认构造方法,防止外部构造类的实例

* */

private Key() {

}

/**

* 获得Key的唯一实例

* */

public static Key getInstance() {

return keygen;

}

/**

* 用指定的表和字段获得key的下一个值,主键的值不得超过2147483647

*

* @param tableName

*            数据库中的表名,表中必须有一个数字主键

* @param keyName

*            表(tableName)中的字段名

* @param conn

*            JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的下一个主键的int值

* @throws KeyException

*         如果表名或字段名不存在、访问数据库错误或key的值大于2147483647时抛出

*/

public int getNextKey(String tableName, String keyName, Connection conn)

throws KeyException {

long value = getNextKeyLong(tableName, keyName, conn);

if (value > 2147483647L) {

throw new KeyException(

"Key's value too big,please call getNextKeyLong method!");

}

return (new Long(value)).intValue();

}

/**

* 用指定的表和字段获得key的下一个值,最大为9223372036854775807

* @param tableName 数据库中的表名,表中必须有一个数字主键

* @param keyName 表(tableName)中的字段名

* @param conn JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的下一个主键的long值

* @throws KeyException 如果表名或字段名不存在或访问数据库错误时抛出

*/

public long getNextKeyLong(String tableName, String keyName, Connection conn)

throws KeyException {

KeyInfo keyinfo;

String item = tableName + "." + keyName;

try {

if (keyList.containsKey(item)) {

keyinfo = (KeyInfo) keyList.get(item);

} else {

keyinfo = new KeyInfo(tableName, keyName, conn);

keyList.put(item, keyinfo);

}

return keyinfo.getNextKey();

} catch (SQLException sqle) {

throw new KeyException(sqle);

}

}

/**

* 用指定的"表.字段"形式的字符串获得key的下一个值,主键的值不得超过2147483647

* @param tableDotField "表.字段"形式的字符串,如:message.id

* @param conn JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的下一个主键的int值

* @throws KeyException 如果表名或字段名不存在、访问数据库错误或key的值 大于2147483647时抛出

*/

public int getNextKey(String tableDotField, Connection conn)

throws KeyException {

long value = getNextKeyLong(tableDotField, conn);

if (value > 2147483647L) {

throw new KeyException(

"Key's value too big,please call getNextKeyLong method!");

}

return (new Long(value)).intValue();

}

/**

* 用指定的"表.字段"形式的字符串获得key的下一个值,最大为9223372036854775807

* @param tableDotField "表.字段"形式的字符串,如:message.id

* @param conn JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的下一个主键的int值

* @throws KeyException 如果表名或字段名不存在或访问数据库错误时抛出

*/

public long getNextKeyLong(String tableDotField, Connection conn)

throws KeyException {

int dot_index = tableDotField.indexOf(".");

if (tableDotField.indexOf(".") 

throw new KeyException("Unknown Key '" + tableDotField + "'!");

}

String tab = tableDotField.substring(0, dot_index);

String key = tableDotField.substring(dot_index);

return getNextKeyLong(tab, key, conn);

}

/**

* 用指定的表和字段获得key的当前值,主键的值不得超过2147483647

* @param tableName 数据库中的表名,表中必须有一个数字主键

* @param keyName 表(tableName)中的字段名

* @param conn JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的当前int值

* @throws KeyException

*         如果表名或字段名不存在、访问数据库错误或key的值大于2147483647时抛出

*/

public int getCurrentKey(String tableName, String keyName, Connection conn)

throws KeyException {

long value = getCurrentKeyLong(tableName, keyName, conn);

if (value > 2147483647L) {

throw new KeyException(

"Key's value too big,please call getCurrentKeyLong method!");

}

return (new Long(value)).intValue();

}

/**

* 用指定的表和字段获得key的当前值,最大为9223372036854775807

*

* @param tableName

*            数据库中的表名,表中必须有一个数字主键

* @param keyName

*            表(tableName)中的字段名

* @param conn

*            JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的当前long值

* @throws KeyException 如果表名或字段名不存在或访问数据库错误时抛出

*/

public long getCurrentKeyLong(String tableName, String keyName,

Connection conn) throws KeyException {

KeyInfo keyinfo;

String item = tableName + "." + keyName;

try {

synchronized (keyList) {

if (keyList.containsKey(item)) {

keyinfo = (KeyInfo) keyList.get(item);

} else {

keyinfo = new KeyInfo(tableName, keyName, conn);

keyList.put(item, keyinfo);

}

}

return keyinfo.getCurrentKey();

} catch (SQLException sqle) {

throw new KeyException(sqle);

}

}

/**

* 用指定的"表.字段"形式的字符串获得key的当前值,主键的值不得超过2147483647

*

* @param tableDotField

*            "表.字段"形式的字符串,如:message.id

* @param conn

*            JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的当前int值

* @throws KeyException 如果表名或字段名不存在、访问数据库错误或key的值

*         大于2147483647时抛出

*/

public int getCurrentKey(String tableDotField, Connection conn)

throws KeyException {

long value = getCurrentKeyLong(tableDotField, conn);

if (value > 2147483647L) {

throw new KeyException(

"Key's value too big,please call getNextKeyLong method!");

}

return (new Long(value)).intValue();

}

/**

* 用指定的"表.字段"形式的字符串获得key的当前值,最大为9223372036854775807

*

* @param tableDotField

*            "表.字段"形式的字符串,如:message.id

* @param conn

*            JDBC连接,如果欲获得的key是第一次取值,则必须保证conn能连接到数据库

* @return key的当前int值

* @throws KeyException 如果表名或字段名不存在或访问数据库错误时抛出

*/

public long getCurrentKeyLong(String tableDotField, Connection conn)

throws KeyException {

int dot_index = tableDotField.indexOf(".");

if (tableDotField.indexOf(".") 

throw new KeyException("Unknown Key '" + tableDotField + "'!");

}

String tab = tableDotField.substring(0, dot_index);

String key = tableDotField.substring(dot_index);

return getCurrentKeyLong(tab, key, conn);

}

}

/**

* 内部类,用来存储主键信息

* */

class KeyInfo {

private long max = 9223372036854775807L;

private long min = 1L;

private long nextKey;

private String tableName;

private String keyName;

private Connection conn = null;

/**

* keyInfo 对象初始化

*

* @throws KeyException

*/

KeyInfo(String tableName, String keyName, Connection _conn)

throws SQLException, KeyException {

this.tableName = tableName;

this.keyName = keyName;

this.conn = _conn;

retrieveFromDB();

}

int getMax() {

return (new Long(max)).intValue();

}

long getMaxLong() {

return max;

}

int getMin() {

return (new Long(min)).intValue();

}

long getMinLong() {

return min;

}

/**

* 取下一键值

*/

int getNextKey() {

return (new Long(getNextKeyLong())).intValue();

}

/**

* 取下一键值

*/

synchronized long getNextKeyLong() {

nextKey++;

return nextKey;

}

/**

* 取当前键值

*/

synchronized int getCurrentKey() {

return (new Long(nextKey)).intValue();

}

/**

* 取当前键值

*/

synchronized long getCurrentKeyLong() {

return nextKey;

}

/**

* 从数据库中取当前最大值

*

* @throws KeyException

*/

void retrieveFromDB() throws SQLException, KeyException {

PreparedStatement pstmt = null;

ResultSet rs = null;

String sql = "select max(" + keyName + ") from " + tableName;

try {

pstmt = conn.prepareStatement(sql);

} catch (Exception ex) {

throw new KeyException("Can't connect DataBase!");

}

try {

rs = pstmt.executeQuery();

} catch (SQLException sqle) {

if (pstmt != null)

pstmt.close();

throw new KeyException("'" + keyName + "' or '" + tableName

+ "' isn't exist in DataBase!", sqle);

}

try {

if (rs.next()) {

nextKey = rs.getLong(1);

if (nextKey 

nextKey = min;

}

} else {

nextKey = min;

}

} catch (SQLException sqle) {

throw (sqle);

} finally {

if (rs != null)

rs.close();

if (pstmt != null)

pstmt.close();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public synchronized String nextId() { long timestamp = timeGen(); //获取当前毫秒数 //如果服务器时间有问题(时钟后退) 报错。 if (timestamp < lastTimestamp) { throw new RuntimeException(String.format( "Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果上次生成时间和当前时间相同,在同一毫秒内 if (lastTimestamp == timestamp) { //sequence自增,因为sequence只有12bit,所以和sequenceMask相与一下,去掉高位 sequence = (sequence + 1) & sequenceMask; //判断是否溢出,也就是每毫秒内超过4095,当为4096时,与sequenceMask相与,sequence就等于0 if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); //自旋等待到下一毫秒 } } else { sequence = 0L; //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加 } lastTimestamp = timestamp; long suffix = (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; String datePrefix = DateFormatUtils.format(timestamp, "yyyyMMddHHMMssSSS"); return datePrefix + suffix; } protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } protected long timeGen() { return System.currentTimeMillis(); } private byte getLastIP(){ byte lastip = 0; try{ InetAddress ip = InetAddress.getLocalHost(); byte[] ipByte = ip.getAddress(); lastip = ipByte[ipByte.length - 1]; } catch (UnknownHostException e) { e.printStackTrace(); } return lastip; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值