InnoDB锁读直到写完成

  • 本文关键字:InnoDB java mysql innodb
  • 更新时间 :
  • 英文 :


我有2个服务器(两个连接),问题是,当服务器A写目录和服务器B中的用户同时请求目录时,他得到旧的结果,而不是新的。有什么方便的方法来解决这个问题?

private synchronized String readDirectory(String entry, Path directory) {
String selectSql = "SELECT directory FROM entries WHERE path = ?";
try (PreparedStatement selectStatement = connection.prepareStatement(selectSql)) {
selectStatement.setString(1, entry);
try (ResultSet rs = selectStatement.executeQuery()) {
if (rs.next()) {
return PathUtils.parseDigest(rs.getString("directory"));
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return NO_DIRECTORY;
}
private synchronized void writeDirectory(String entry, Path directory) {
String pathString = PathUtils.toString(directory);
String insertSql = "INSERT or REPLACE INTO entries (path, directory) VALUES (?,?)";
try (PreparedStatement insertStatement = connection.prepareStatement(insertSql)) {
insertStatement.setString(1, entry);
insertStatement.setString(2, pathString);
insertStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

我的简单解释是:关键字synchronized只在同一个java应用程序进程中工作。如果多个java应用程序进程请求共享数据库,可以使用分布式锁来避免并发更新。或者您可以使用数据库共享/独占锁:lock in share modefor update。例如:SELECT directory FROM entries WHERE path = ?更新;

最新更新