java生成分布式随机文件名
时间: 2023-10-05 20:13:45 浏览: 105
可以使用Snowflake算法生成分布式随机文件名,示例代码如下:
```java
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class DistributedRandomFileNameGenerator {
private static final long EPOCH = 1420041600000L; // 2015-01-01
private static final int NODE_ID_BITS = 10;
private static final int SEQUENCE_BITS = 12;
private static final long MAX_NODE_ID = (1L << NODE_ID_BITS) - 1;
private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;
private final long nodeId;
private long lastTimestamp = -1L;
private long sequence = 0L;
public DistributedRandomFileNameGenerator(long nodeId) {
if (nodeId < 0 || nodeId > MAX_NODE_ID) {
throw new IllegalArgumentException(String.format("NodeId must be between 0 and %d", MAX_NODE_ID));
}
this.nodeId = nodeId;
}
public synchronized String generate() {
long timestamp = System.currentTimeMillis() - EPOCH;
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
long id = ((timestamp << (NODE_ID_BITS + SEQUENCE_BITS)) | (nodeId << SEQUENCE_BITS) | sequence) & Long.MAX_VALUE;
return Long.toString(id, 36);
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis() - EPOCH;
while (timestamp <= lastTimestamp) {
timestamp = System.currentTimeMillis() - EPOCH;
}
return timestamp;
}
public static void main(String[] args) throws IOException {
DistributedRandomFileNameGenerator generator = new DistributedRandomFileNameGenerator(1);
String fileName = generator.generate();
System.out.println(fileName);
// Save nodeId and lastTimestamp to file for recovery
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
ObjectNode node = mapper.createObjectNode();
node.put("nodeId", generator.nodeId);
node.put("lastTimestamp", generator.lastTimestamp);
mapper.writeValue(new File("generator.json"), node);
}
}
```
上述代码中,`DistributedRandomFileNameGenerator`类使用Snowflake算法生成分布式随机文件名。在构造函数中指定节点ID,然后调用`generate()`方法即可生成随机文件名。为了防止时钟回拨等问题,需要在生成文件名时保证时间戳单调递增。如果需要在重启程序后恢复生成器状态,可以将节点ID和上一次生成文件名的时间戳保存到文件中,然后在程序启动时读取该文件,恢复生成器状态。
阅读全文