日期格式 雪花算法 java
时间: 2023-08-28 12:18:00 浏览: 155
java 日期算法
日期格式是指在编程中表示日期的方式。在Java中,可以使用`java.util.Date`类或`java.time.LocalDate`类来表示日期。日期格式可以使用`SimpleDateFormat`类来进行格式化和解析。
雪花算法是一种分布式唯一ID生成算法,它可以生成全局唯一且有序的ID。在Java中,可以使用Snowflake算法实现ID的生成。Snowflake算法的核心思想是将一个64位的long型ID分成多个部分,每个部分表示不同的信息,例如时间戳、机器ID、数据中心ID、序列号等。
以下是一个使用Snowflake算法生成ID的Java示例代码:
```java
public class SnowflakeIdGenerator {
private final long epoch = 1609459200000L;
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long sequenceBits = 12L;
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public SnowflakeIdGenerator(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException("Worker ID can't be greater than " + maxWorkerId + " or less than 0");
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException("Datacenter ID can't be greater than " + maxDatacenterId + " or less than 0");
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public synchronized long generateId() {
long timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate ID for " + (lastTimestamp - timestamp) + " milliseconds");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - epoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift)
| sequence;
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis();
}
return timestamp;
}
}
```
使用示例:
```java
SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
long id = idGenerator.generateId();
System.out.println(id);
```
这样就可以生成一个唯一的ID了。请注意,Snowflake算法中的workerId和datacenterId需要根据具体的分布式系统进行设置。
阅读全文