游小安的gravatar头像
游小安 2015-10-29 09:06:01

java如何编写类似oracle自增序列的算法?

求大神给写一个java自增方法,类似于Oracle自增序列那种的,范围从1增到200就够了!多谢多谢

所有回答列表(6)
最代码官方的gravatar头像
最代码官方  LV167 2015年10月31日

如果你的这个值是用来做数据库的表数据唯一标识的话,建议可以用twitter idworker的算法,支持分布式部署生成,性能极高,也是支持排序的。

想找一个java版本的twitter的IdWorker的代码

package com.idworker;

public class IdWorker {
	private final long workerId;
	private final static long twepoch = 1288834974657L;
	private long sequence = 0L;
	private final static long workerIdBits = 4L;
	public final static long maxWorkerId = -1L ^ -1L << workerIdBits;
	private final static long sequenceBits = 10L;

	private final static long workerIdShift = sequenceBits;
	private final static long timestampLeftShift = sequenceBits + workerIdBits;
	public final static long sequenceMask = -1L ^ -1L << sequenceBits;

	private long lastTimestamp = -1L;

	public IdWorker(final long workerId) {
		super();
		if (workerId > this.maxWorkerId || workerId < 0) {
			throw new IllegalArgumentException(String.format(
					"worker Id can't be greater than %d or less than 0",
					this.maxWorkerId));
		}
		this.workerId = workerId;
	}

	public synchronized long nextId() {
		long timestamp = this.timeGen();
		if (this.lastTimestamp == timestamp) {
			this.sequence = (this.sequence + 1) & this.sequenceMask;
			if (this.sequence == 0) {
				System.out.println("###########" + sequenceMask);
				timestamp = this.tilNextMillis(this.lastTimestamp);
			}
		} else {
			this.sequence = 0;
		}
		if (timestamp < this.lastTimestamp) {
			try {
				throw new Exception(
						String.format(
								"Clock moved backwards.  Refusing to generate id for %d milliseconds",
								this.lastTimestamp - timestamp));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		this.lastTimestamp = timestamp;
		long nextId = ((timestamp - twepoch << timestampLeftShift))
				| (this.workerId << this.workerIdShift) | (this.sequence);
		System.out.println("timestamp:" + timestamp + ",timestampLeftShift:"
				+ timestampLeftShift + ",nextId:" + nextId + ",workerId:"
				+ workerId + ",sequence:" + sequence);
		return nextId;
	}

	private long tilNextMillis(final long lastTimestamp) {
		long timestamp = this.timeGen();
		while (timestamp <= lastTimestamp) {
			timestamp = this.timeGen();
		}
		return timestamp;
	}

	private long timeGen() {
		return System.currentTimeMillis();
	}
	
	
	public static void main(String[] args){
		IdWorker worker2 = new IdWorker(2);
		System.out.println(worker2.nextId());
	}

}	    			
评论(0) 最佳答案
无天无极的gravatar头像
无天无极  LV6 2015年10月29日

新加一个字段 每次调用之后加1保存

游小安的gravatar头像
游小安  LV8 2015年10月29日

就是想写一个java工具类,不用操作数据库的!

遇见,的gravatar头像
遇见,  LV36 2015年10月29日

在工具类里写个变量用static修饰, 每次操作+1

只需要在系统关闭前把这个值存到数据库或文件   系统打开时把这个值取出来赋给这个变量

heroshen的gravatar头像
heroshen  LV7 2015年10月29日

如果只是使用变量的话,重启一下就会清零

不想用数据库可以写入一个文件中

lihuai的gravatar头像
lihuai  LV4 2015年10月30日

这种要分情形的,分布式系统要用统一内存控制的,不然肯定冲突,单一就直接加1就可以了

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友