2016-01-20 131 views
0

我有一種方法,必須從用戶上傳的原始文件中創建一個zip和mat文件。 所以我決定只存儲原始文件,然後在異步任務中我想創建其他兩個文件。 我讀了@Async註釋有兩個限制: 1)只有在公共方法 2)@Async方法必須在不同的對象尊重調用方類。 所以我創建了一個新類,並將其放入我的異步方法中,但它仍然沒有工作。 這是調用異步方法的類:@Async Spring註解不起作用

@Service 
public class FleetAcquisitionServicesImpl implements FleetAcquisitionServices{ 

    @Autowired 
    private DatabaseAcquisitionServices databaseAcquisitionServices; 
    @Autowired 
    private DatabaseFleetsAndCarsServices databaseFleetsAndCarsServices; 

    @Autowired 
    private FleetFolderName fleetFolderName; 

    private static final int NUMBER_OF_SHEET=4; 
    @Override 
    public ArrayList<String> uploadFiles(MultipartFile[] openedFiles, Integer idFleet, Integer idCar, Integer initialKm) throws FileUploadException, FileEmptyException{ 
     ArrayList<String> filesName=new ArrayList<String>(); 
     String fileName=null; 
     String carPath=null; 
     for (MultipartFile openedFile:openedFiles){ 
      if (!openedFile.isEmpty()) { 
       //Copy the file into path specified 
       fileName = openedFile.getOriginalFilename(); 
       try { 
        //Get the path where to store the file 
        Fleet fleet=databaseFleetsAndCarsServices.getFleetById(idFleet); 
        Car car=databaseFleetsAndCarsServices.getCarById(idCar); 
        carPath= fleetFolderName.createCarName(fleet, car); 
        if (FilenameUtils.getExtension(fileName).equals("dat")){ 
         fileName = FilenameUtils.removeExtension(fileName)+"_km"+initialKm; 
         //write dat file 
         openedFile.transferTo(new File(carPath +"/"+ fileName+".dat"));     
         ZipAndMat.createZipAndMat(carPath,fileName); 
        }else 
         openedFile.transferTo(new File(carPath +"/"+ fileName)); 
       } catch (Exception e) { 
        throw new FileUploadException("you failed to upload " + fileName,e); 
       } 
       filesName.add(carPath +"/"+ fileName); 
      } else { 
       throw new FileEmptyException("your file is empty " + openedFile.getOriginalFilename()); 
      } 
     } 
     return filesName; 
    } 

ZipAndMat.createZipAndMat(carPath,fileName) 

是異步方法,它是在這裏:

package com.model; 

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.concurrent.Future; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipOutputStream; 

import org.springframework.scheduling.annotation.Async; 
import org.springframework.scheduling.annotation.AsyncResult; 

import com.mathworks.toolbox.javabuilder.MWException; 

import dataconversion.Converter; 

public class ZipAndMat { 


    @Async 
    public static Future<String> createZipAndMat(String filePath, String fileName){ 
     try { 
      Thread.sleep(20000L); 
     } catch (InterruptedException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     //Open file 
     Path path = Paths.get(filePath, fileName + ".dat"); 
     try { 
      //Create zip 
      byte[] zip = zipBytes(Files.readAllBytes(path),fileName+".dat"); 
      Files.write(Paths.get(filePath +"/"+ fileName+".zip"), zip); 
      //create mat file 
      Converter objConv = new Converter(); 
      objConv. dat2MatConversion(filePath +"/", fileName + ".dat", 0.2); 
     } catch (IOException e) { 
      return new AsyncResult<String>("Zip not created"); 
     } catch (MWException e){ 
      return new AsyncResult<String>("Mat not created"); 
     } 
     return new AsyncResult<String>("Zip created"); 
    } 

    /** 
    * Convert a file into zip file keeping the same name 
    * @param filename 
    * @param input 
    * @return 
    * @throws IOException 
    */ 
    private static byte[] zipBytes(byte[] input, String filename) throws IOException { 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     ZipOutputStream zos = new ZipOutputStream(baos); 
     ZipEntry entry = new ZipEntry(filename); 
     entry.setSize(input.length); 
     zos.putNextEntry(entry); 
     zos.write(input); 
     zos.closeEntry(); 
     zos.close(); 
     return baos.toByteArray(); 
    } 

} 

我試圖TU但@EnableAsync兩個主叫類的confiuration類,但它不起作用。 我的代碼有什麼問題?靜態方法? 感謝

+1

我對彈簧一無所知,但通過https://spring.io/guides/gs/async-method/ show您需要在'@Service'上調用該方法 - 它們的示例使用非靜態方法。否則,你只是調用'createZipAndMat'作爲普通的舊靜態方法 - 不存在異步性的可能性。你確定你的2個要求是足夠的嗎? –

+0

ZipandMat應該是一個春天的豆子.. – ArunM

+0

我試過添加@Component,但它不起作用 – luca

回答

2

你需要以下幾件事:在配置類

  1. @EnableAsync啓用異步處理春天。
  2. @Service@Component您的ZipAndMat類將其作爲Spring組件發現。
  3. 更改createZipAndMat方法,因此它的不是靜態的
  4. 自動裝配在FleetAcquisitionServicesImpl這個新的Spring組件是這樣的:

    @Autowired private ZipAndMat zipAndMat;

然後,而不是調用靜態方法ZipAndMat.createZipAndMat(carPath,fileName);你需要調用它像自動裝配Autowired彈簧組件實例這個:

zipAndMat.createZipAndMat(carPath,fileName); 
+0

刪除靜態它的作品。我沒有發現有關異步註釋的靜態內容。謝謝 – luca

+0

是的。這種魔術'@ EnableAsync'通常只適用於彈簧組件。所以你需要'@ Component'或'@ Service'和普通的實例方法來使Spring能夠完成它的工作。閱讀更多關於春天是什麼以及如何做的真的很值得,它從長遠來看是值得的。 –

1

你需要做下面的事情,使異步

1) @Service 公共類ZipAndMat ...

2)來電類應該使用@EnableAsync

使異步調用

@EnableAsync @Service 公共類FleetAcquisitionServicesImpl實現FleetAcquisitionServices

請點擊此鏈接查看更多細節 https://spring.io/guides/gs/async-method/

+0

我向ZipAndMat添加了「@Services」,爲FleetAcquisitionServicesImpl添加了「@EnableAsync」,但我仍然需要等待ZipAndMat結束。 – luca

+0

你試過去除靜電嗎? –