java生成唯一数字

来源:互联网 发布:网络爬虫用什么语言好 编辑:程序博客网 时间:2024/06/05 07:45
用UUID类生成唯一标识的时候,会生成一个十六进制的整数,但是不能作为数据库long型字段的唯一标识,用下面的办法可以实现数据库long型标识的生成:
public class ProfileUtil {

    private static AtomicInteger counter = new AtomicInteger(0);

    /**
     * 长生消息id
     */
    public static long getAtomicCounter() {
        if (counter.get() > 999999) {
            counter.set(1);
        }
        long time = System.currentTimeMillis();
        long returnValue = time * 100 + counter.incrementAndGet();
        return returnValue;
    }

    private static long incrementAndGet() {
        return counter.incrementAndGet();
    }

    public static void main(String[] args) {
        
        System.out.println(ProfileUtil.getAtomicCounter());
    }
    
    
}
但是请注意,如果将系统部署到集群上面,情况有会有不同了,不同的服务器集群生成的这个数字,是有重合的概率的,因此,一般情况是,将集群中的每个机器进行编码,然后将机器编码放在这个标识的前面以示区分。
原创粉丝点击