java生成不重复的id_Java 生成永不重复的ID的代码

package com.hh.util;

/**

*

* 创建数据库ID的通用方法.

* @since JDK1.6

*/

public class CreateID {

private final static String str = "1234567890abcdefghijklmnopqrstuvwxyz";

private final static int pixLen = str.length();

private static volatile int pixOne = 0;

private static volatile int pixTwo = 0;

private static volatile int pixThree = 0;

private static volatile int pixFour = 0;

/**

* 生成短时间内不会重复的长度为15位的字符串,主要用于ISSP-MOC模块数据库主键生成使用。

* 生成策略为获取自1970年1月1日零时零分零秒至当前时间的毫秒数的16进制字符串值,该字符串值为11位

* 并追加四位"0-z"的自增字符串.

* 如果系统时间设置为大于2304-6-27 7:00:26的时间,将会报错!

* 由于系统返回的毫秒数与操作系统关系很大,所以本方法并不准确。本方法可以保证在系统返回的一个毫秒数内生成36的4次方个(1679616)ID不重复。

*

* @return 15位短时间不会重复的字符串。

* @author lixunhui@qq.com

* @since JDK1.6

*/

final public synchronized static String generate() {

StringBuilder sb = new StringBuilder();// 创建一个StringBuilder

sb.append(Long.toHexString(System.currentTimeMillis()));// 先添加当前时间的毫秒值的16进制

pixFour++;

if (pixFour == pixLen) {

pixFour = 0;

pixThree++;

if (pixThree == pixLen) {

pixThree = 0;

pixTwo++;

if (pixTwo == pixLen) {

pixTwo = 0;

pixOne++;

if (pixOne == pixLen) {

pixOne = 0;

}

}

}

}

return sb.append(str.charAt(pixOne)).append(str.charAt(pixTwo)).append(str.charAt(pixThree)).append(str.charAt(pixFour)).toString();

}

/**

* 随机创建数据库15位ID

*

* @return String 15位随机数ID

*/

/*

* public synchronized static String generate() { Long _ruleId1 =

* Long.valueOf(Calendar.getInstance().getTimeInMillis()); Integer _ruleId2

* = Integer.valueOf(i++); if (i > 99) { i = 10; } return (new

* Long(_ruleId1.toString() + _ruleId2.toString())).toString(); }

*/

/**

* 随机创建数据库9位ID

*

* @return String 9位随机数ID

*/

public synchronized static String generate9() {

int n = (int) (Math.random() * 900000000) + 100000000;

return n + "";

}

/**

* 创建15位字母加数字ID

* bl 为true是为暂停时间

*

* @return string 15位随机ID

*/

public synchronized static String generateStrID(String str) {

int count = 0;

String time = Long.toString(System.currentTimeMillis());

time = time.substring(time.length() - 9, time.length());

if (count > 99) {

count = 0;

} else {

count++;

}

if (count < 10) {

str += time + "0" + count;

} else {

str += time + count;

}

return str;

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值