1. 程式人生 > >spring 非同步上傳檔案給第三方

spring 非同步上傳檔案給第三方


import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import com.itrus.laweyecloud.pojo.FileOfBillWrap;
/**
 * 測試非同步的執行檔案上傳,可以成功的支援多執行緒和非同步
 * @author 
 *
 */
@Component
public class AsyncTaskFileUploadTaskService {

	@Autowired
	private FileUpLoadTaskService fileUpLoadTaskService;
	
	@Async
	public void excuteAsyncTaskFileUpload(FileOfBillWrap fileOfBillWrap){
		try {
			fileUpLoadTaskService.uploadFileToWuzhong(fileOfBillWrap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Async
	public Future<Boolean> excuteAsyncTaskFileUploadWithResult(FileOfBillWrap fileOfBillWrap){
		boolean result = false;
		try {
			result = fileUpLoadTaskService.uploadFileToWuzhong(fileOfBillWrap);
			return new AsyncResult<Boolean>(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AsyncResult<Boolean>(result);
	}
}


import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @Author 
 * @Description
 * @Date Created in 2018/1/24
 * 定時上傳本地檔案
 * 每隔10分鐘執行一次
 * 1:判斷佇列是否為空,空則執行步驟2,否則不執行
 * 2:查詢fileOfBill表(source為1,isUpLoad為false)
 * 3:呼叫佇列上傳檔案
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class FileUpLoadTask {

    private final static Logger logger = LoggerFactory.getLogger(FileUpLoadTask.class);

    @Autowired
    private FileOfBillService fileOfBillService;

    @Autowired
    private ThreadPoolManager tpm;

    public static final String LOCK = "FileUploadTaskLock";

    @Autowired
    private FileUpLoadTaskService fileUpLoadTaskService;
    @Autowired
    AsyncTaskFileUploadTaskService asyncTaskFileUploadTaskService;

    @Scheduled(cron = "0/10 * * * * ?")
    public  void upLoadFile() {
        synchronized (LOCK){
            // 1:查詢fileOfBill表
            Map<String, Object> p = new HashedMap();
            p.put("isUpload", false);
            p.put("source", ComNamesOfFile.SOURCE_1);
            try {
                List<FileOfBill> list = fileOfBillService.getListByParam(p);
                List<FileOfBillWrap> fileOfBillWraps = fileOfBillService.downLoadFile(list);

                // 2:呼叫佇列上傳檔案
                for (FileOfBillWrap fileOfBillWrap : fileOfBillWraps) {
                    try {
                    	System.out.println("Invoking an asynchronous method. "+ Thread.currentThread().getName());
                        //fileUpLoadTaskService.uploadFileToWuzhong(fileOfBillWrap);
                    	/**
                    	 * Result from asynchronous process - true
						   Invoking an asynchronous method. pool-3-thread-1
						   Continue doing something else. 
                    	 */
                    	Future<Boolean> future = asyncTaskFileUploadTaskService.excuteAsyncTaskFileUploadWithResult(fileOfBillWrap);
                        while (true) {  ///這裡使用了迴圈判斷,等待獲取結果資訊
                            if (future.isDone()) {  //判斷是否執行完畢
                                System.out.println("Result from asynchronous process - " + future.get());
                                break;
                            }
                            System.out.println("Continue doing something else. ");
                            Thread.sleep(1000);
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
            } catch (Exception e) {
                logger.error("Class FileUpLoadTask, timed task upLoadFile execution exception", e);
            }
        }
    }
}