2016-01-20 86 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

你试过去除静电吗? –