1. 程式人生 > >多檔案上傳、excel多檔案匯入(大量資料)

多檔案上傳、excel多檔案匯入(大量資料)

多檔案上傳、excel多檔案匯入(大量資料)
置頂2018年03月02日 14:52:32

閱讀數:436

問題:多個excel檔案匯入(上傳)

思路:由於檔案選擇只能單個檔案選擇,那麼可以將excel檔案一個一個上傳到本地或伺服器,將路徑儲存至資料庫中,後臺使用佇列進行操作,即上傳第一個檔案時便在後臺開啟一條執行緒,注意是隻開啟一條如果多條會導致死鎖等各種問題,開啟執行緒後,將陸續上傳的檔案加入佇列中,只要佇列中有資料就不結束執行緒,直到佇列中的資料全部執行完也就是前端上傳的檔案全部匯入到資料庫中就結束執行緒。前端提供進度條。即能上傳大量資料又不影響前端頁面的操作,只需檢視進度條即可知道資料上傳量。

效果圖片:



後臺實現程式碼:

1、將上傳的檔案一個個加入佇列中

首先將所有上傳檔案存到本地或者伺服器,將路徑儲存到資料庫

String filePath = fileService.upload(FileInfo.FileType.file, file, true, null); ImportLog importLog = importLogService.putDownTask(total, file.getOriginalFilename(), filePath); importSubject.addTask(importLog);

再講一個個存到資料庫中的檔案路徑放到佇列中。addTask();方法如下

@Resource(name = "productImportSubscriber") private ImportSubscriber importSubscriber; @Resource(name = "taskExecutor") private ThreadPoolTaskExecutor threadPool;

@Resource(name = "importEvent") private ImportEvent importEvent;

public void addTask(ImportLog importLog) { importSubscriber.add(importLog); if (!importEvent.isRunning()) { threadPool.execute(new Runnable() { @Override public void run() { importSubscriber.start(); } }); } }

判斷isRunning是否在啟動,所有每次只有一個檔案在匯入,並不會出現其他資源爭搶的情況。

_/** _ * _觀察者介面 _ */ public interface ImportSubscriber {

Boolean start();

**void** add(ImportLog importLog);

}

實現ImportSubscriber介面:

public static Queue queue = new LinkedList<>();

@Override public Boolean start() { importData();//此處就可以處理不同系統的業務邏輯,比如匯入資料 return true; }

@Override public void add(ImportLog importLog) { queue.add(importLog); }

到這裡多檔案匯入就結束了,從全域性看,這種方式只是比較巧妙了運用了佇列。比如如果你要匯入一個excel檔案,有100W+的資料,那麼前端

會非常慢,導致那個頁面除了一直匯入以外什麼事也做不了,那麼使用者體驗就非常差,而這裡是先將檔案儲存起來,

在後臺慢慢執行,而前端只是給了一個進度條,可以告知使用者什麼時候能匯入完。