优化UUID

1,507 阅读1分钟

数据ID生成方案中UUID相对来说是最简单的,但是其也有不少缺点:

1.没有排序,无法保证趋势递增。 2.UUID往往是使用字符串存储,查询的效率比较低。 3.存储空间比较大,如果是海量数据库,就需要考虑存储量的问题。 4.传输数据量大 5.不可读。

常见优化方案: 1.优化字符串为BigInteger

private static BigInteger pair() {
  UUID myuuid = UUID.randomUUID();
  //UUID长度为128位
  ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
  bb.putLong(myuuid .getMostSignificantBits());
  bb.putLong(myuuid .getLeastSignificantBits());
  return new BigInteger(bb.array());
}

2.去掉符号:

private static BigInteger pair(UUID uuid) {
	BigInteger value1 = BigInteger.valueOf(uuid.getMostSignificantBits());
	BigInteger value2 = BigInteger.valueOf(uuid.getLeastSignificantBits());
	if (value1.compareTo(value2) < 0) {
		return value2.multiply(value2).add(value1);
	}
	return value1.multiply(value1).add(value1).add(value2);
}