Java分布式ID
在Java中生成分布式唯一ID的常见方法是使用UUID或者结合数据库生成唯一ID。以下是一个使用数据库生成唯一ID的例子:
- 在数据库中创建一个序列(如果数据库支持的话)。
- 在插入新记录时,使用该序列生成唯一ID。
以下是一个简单的例子,使用MySQL数据库和JDBC来生成分布式唯一ID:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
public class DistributedIdGenerator {
private static final String DB_URL = "jdbc:mysql://localhost:3306/yourdatabase";
private static final String USER = "yourusername";
private static final String PASS = "yourpassword";
private static final String INSERT_SQL = "INSERT INTO your_table (id, data) VALUES (?, ?)";
private static final String GET_NEXT_ID_SQL = "SELECT LAST_INSERT_ID()";
public static String generateId() {
return UUID.randomUUID().toString();
}
public static long getNextId(String connectionId) throws SQLException {
try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS)) {
PreparedStatement statement = connection.prepareStatement(GET_NEXT_ID_SQL);
try (ResultSet resultSet = statement.executeQuery()) {
resultSet.next();
return resultSet.getLong(1);
}
}
}
public static void insertData(String id, String data) throws SQLException {
try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS)) {
PreparedStatement statement = connection.prepareStatement(INSERT_SQL);
statement.setString(1, id);
statement.setString(2, data);
statement.executeUpdate();
}
}
public static void main(String[] args) {
try {
String id = generateId();
insertData(id, "Some data");
long nextId = getNextId(id);
System.out.println("Generated ID:
评论已关闭