简体   繁体   English

如何在 Java/Scala 中生成 TimeUUID

[英]How to generate TimeUUID in Java/Scala

Does anyone know how to generate TimeBased UUIDs in Java/Scala?有谁知道如何在 Java/Scala 中生成基于时间的 UUID?

Here is the column family:这是列族:

CREATE table col(ts timeuuid)

I'm using Cassandra 1.2.4我正在使用 Cassandra 1.2.4

Appreciate your help!感谢你的帮助!

If you are using the Datastax drivers you can use the utility class, UUIDs , to generate one 如果您使用的是Datastax驱动程序,则可以使用实用程序类UUID生成一个

import com.datastax.driver.core.utils.UUIDs;
....
UUID timeBasedUuid = UUIDs.timeBased();

Cassandra has UUIDGen for generating Timeuuids. Cassandra有UUIDGen用于生成Timeuuids。 The source for this is here: 这里的来源是:

https://github.com/apache/cassandra/blob/cassandra-2.1/src/java/org/apache/cassandra/utils/UUIDGen.java https://github.com/apache/cassandra/blob/cassandra-2.1/src/java/org/apache/cassandra/utils/UUIDGen.java

i am using the same way for cassandra cli, and for column name i am using 我使用相同的方式cassandra cli,以及我正在使用的列名

System.currentTimeMillis().toString

scala>     val timestamp = System.currentTimeMillis().toString
timestamp: String = 1406279679674

UPDATE UPDATE

mainly it depends on your row key if rowKey is your userId or something, then there is no chance of submission of duplicate record in miliseconds but if you think it can be repeat then use 主要取决于你的行键,如果rowKey是你的userId或什么的,那么就没有机会在几毫秒内提交重复记录,但如果你认为它可以重复那么使用

val timestamp = com.eaio.uuid.UUIDGen.newTime().toString

this is work for cassandra 4.x version这适用于 cassandra 4.x 版本

first, import libary in build.sbt首先,在build.sbt中导入库

libraryDependencies ++= Seq(
  "com.datastax.oss" % "java-driver-core" % "4.15.0"
)

example例子

import com.datastax.oss.driver.api.core.uuid.Uuids

import java.time.ZonedDateTime

object Test extends App {
  val timeText = "2022-01-01T00:01:01.002345Z"
  val datetime = ZonedDateTime.parse(timeText)
  val uuid = Uuids.endOf(datetime.toInstant.toEpochMilli)
  println(uuid) // e79b51af-6a95-11ec-7f7f-7f7f7f7f7f7f
}

test on cassandra在 cassandra 上测试

cqlsh:test> create table aaa (id timeuuid primary key, t text);

cqlsh:test> insert into aaa(id,t) values(e79b51af-6a95-11ec-7f7f-7f7f7f7f7f7f, 't4');

cqlsh:test> select toTimestamp(id), t from aaa;

 system.totimestamp(id)          | t
---------------------------------+----
 2022-01-01 00:01:01.002000+0000 | t4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM