java Sequence生成器

  
import java.sql.Connection;   
import java.sql.PreparedStatement;   
import java.sql.ResultSet;   
import java.sql.SQLException;   
import java.sql.Statement;   
import java.util.HashMap;   
import java.util.Map;   
/**  
*  
* <b>Note</b>: Java实现的Sequence工具  
*/  
public class SequenceUtil {   
           
        /**  
         * 单例模式  
         */  
        private static SequenceUtil instance = new SequenceUtil();   
           
        /**  
         * 存放序列的MAP  
         */  
        private Map<String, KeyInfo> keyMap = new HashMap<String, KeyInfo>(20);   
        private static final int POOL_SIZE = 1;   
        /**  
         * 防止外部实例化  
         */  
        private SequenceUtil() {   
        }   
        /**  
         * 单例模式,获取单例  
         *  
         * @return SequenceUtils的单例对象  
         */  
        public static SequenceUtil getInstance() {   
                return instance;   
        }   
        /**  
         * 获取下一个sequence值  
         *  
         * @param keyName  
         * Sequence名称  
         * @return 下一个Sequence键值  
         */  
        public synchronized int getNextKeyValue(String keyName) {   
                KeyInfo keyInfo = null;   
                Integer keyObject = null;   
                try {   
                        if (keyMap.containsKey(keyName)) {   
                                keyInfo = keyMap.get(keyName);   
                        } else {   
                                keyInfo = new KeyInfo(keyName, POOL_SIZE);   
                                keyMap.put(keyName, keyInfo);   
                        }   
                        keyObject = keyInfo.getNextKey();   
                } catch (SQLException e) {   
                        e.printStackTrace();   
                }   
                return keyObject;   
        }   
}   
class KeyInfo {   
           
        /**  
         * 当前Sequence载体的最大值  
         */  
        private int maxKey;   
           
        /**  
         * 当前Sequence的最小值  
         */  
        private int minKey;   
           
        /**  
         * 下一个Sequence值  
         */  
        private int nextKey;   
           
        /**  
         * Sequence缓存值  
         */  
        private int poolSize;   
           
        /**  
         * Sequence的名称  
         */  
        private String keyName;   
           
        /**  
         * 更新存放Sequence表的语句  
         */  
        private static final String sql_update = "UPDATE intpub_Sequence SET KEYVALUE = KEYVALUE + ? WHERE KEYNAME = ?";   
           
        /**  
         * 查询Sequence表中的当前值  
         */  
        private static final String sql_query = "SELECT KEYVALUE FROM intpub_Sequence WHERE KEYNAME = ?";   
        public KeyInfo(String keyName, int poolSize) throws SQLException {   
                this.poolSize = poolSize;   
                this.keyName = keyName;   
                retrieveFromDB();   
        }   
        public String getKeyName() {   
                return keyName;   
        }   
        public int getMaxKey() {   
                return maxKey;   
        }   
        public int getMinKey() {   
                return minKey;   
        }   
        public int getPoolSize() {   
                return poolSize;   
        }   
        /**  
         * 获取下一个Sequence值  
         *  
         * @return 下一个Sequence值  
         * @throws SQLException  
         */  
        public synchronized int getNextKey() throws SQLException {   
                if (nextKey > maxKey) {   
                        retrieveFromDB();   
                }   
                return nextKey++;   
        }   
        /**  
         * 执行Sequence表初始化和更新工作  
         *  
         * @throws SQLException  
         */  
        private void retrieveFromDB() throws SQLException {   
                Connection conn = ConnectionPool.getInstance().getConnection();   
                // 查询数据库   
                PreparedStatement pstmt_query = conn.prepareStatement(sql_query);   
                pstmt_query.setString(1, keyName);   
                ResultSet rs = pstmt_query.executeQuery();   
                if (rs.next()) {   
                        maxKey = rs.getInt(1) + poolSize;   
                        minKey = maxKey - poolSize + 1;   
                        nextKey = minKey;   
                        rs.close();   
                        pstmt_query.close();   
                } else {   
                        String init_sql = "INSERT INTO intpub_Sequence(KEYNAME,KEYVALUE) VALUES('"  
                                        + keyName + "',10000 + " + poolSize + ")";   
                        Statement stmt = conn.createStatement();   
                        stmt.executeUpdate(init_sql);   
                        maxKey = 10000 + poolSize;   
                        minKey = maxKey - poolSize + 1;   
                        nextKey = minKey;   
                        stmt.close();   
                        return;   
                }   
                // 更新数据库   
                conn.setAutoCommit(false);   
                PreparedStatement pstmt_up = conn.prepareStatement(sql_update);   
                pstmt_up.setLong(1, poolSize);   
                pstmt_up.setString(2, keyName);   
                pstmt_up.executeUpdate();   
                pstmt_up.close();   
                conn.commit();   
                rs.close();   
                pstmt_query.close();   
                conn.close();   
        }   
}  

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值