今天爱分享给大家带来文件的防止多进程读 数据库或FileLock防重复处理【附代码】,希望能够帮助到大家。
服务双活情况下,有可能存在多个应用扫到同一个文件,然后重复处理。可以通过以下做法防止多进程处理同一个文件:
a. (建议该做法)处理文件前,入库insert。并且文件名添加唯一索引,确保同一个文件只会被处理一次。
b. 先尝试加锁文件,成功后移动文件至处理目录。(不需要记表)
锁方法: 通过FileLock获取锁。获取成功后创建锁文件,如果创建成功则锁成功释放锁,否则失败释放锁。代码如下:
// 加锁代码
public static boolean fileLocker(File file) {
boolean flag = false;
FileOutputStream fos = null;
FileLock lock = null;
try {
fos = new FileOutputStream(file, true);
lock = fos.getChannel().tryLock();
if (lock != null) {
File lockFile = new File(file.getParent(), file.getName() + ".lock");
if (lockFile.isFile()) {
lock.release();
flag = false;
} else {
lockFile.createNewFile();
lock.release();
flag = true;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (fos != null)
fos.close();
} catch (Exception e2) {
throw new RuntimeException(e2);
}
}
return flag;
}
//释放锁代码
public static void fileUnLocker(File file) {
File lockFile = new File(file.getParent(), file.getName() + ".lock");
lockFile.delete();
}
// 移动文件代码
public static boolean moveFileWithLock(File file, String path) {
if (file.exists()) {
if (fileLocker(file)) {
try {
if (new File(path, file.getName()).exists()) {
FileUtils.forceDelete(new File(path, file.getName()));
}
FileUtils.moveFileToDirectory(file, new File(path), false);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
fileUnLocker(file);
}
return true;
} else {
throw new RuntimeException("文件["+file.getAbsolutePath()+"]加锁失败,移动失败");
}
} else {
throw new RuntimeException("文件[" + file.getAbsolutePath() + "]不存在,移动失败");
}
}
原文链接:https://blog.itblood.com/4006.html,转载请注明出处。

![城市恶魔:重启 0.4赞助 领先版[PC+安卓/8.89G/更新] [神作SLG/汉化/动态]](/wp-content/uploads/replace/2025/10/17/af051137f5a206c6ecbbaff2d94ff061.webp)