文件的防止多进程读 数据库或FileLock防重复处理【附代码】

今天爱分享给大家带来文件的防止多进程读 数据库或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() + "]不存在,移动失败");
     }
 }



人已赞赏
数据库

远程服务调用防重复处理 通过业务单号做链路幂【附代码】

2020-12-23 14:34:02

数据库

逐笔处理优化为批量处理 针对数据库、redis等减少网络交互,提升性能【附代码】

2020-12-23 14:35:51

'); })();