欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring 异步上传文件给第三方

程序员文章站 2022-03-09 23:31:03
...

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);
            }
        }
    }
}

相关标签: 异步