SpingBoot之優雅的異步方法調用

場景:Java中調用python,有些不穩定,有時候非常快,有時候慢。

在保證不污染原有代碼的基礎上,進行異步方法調用:

 Service代碼:

public interface AsyncService {

    /**
     * 異步執行pathon
     * @param cmdArr
     * @return
     */
    void Async(String[] cmdArr);

}
import com.atage.op.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服務實現類
 * </p>
 *
 * @author 魯達
 * @since 2019-09-05
 */
@Service
public class AsyncServiceImpl implements AsyncService {

    @Async
    @Override
    public void Async(String[] cmdArr) {
        try {
            //要執行的業務代碼
            Runtime.getRuntime().exec(cmdArr);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}

Controller代碼:

類上加註解:@EnableAsync
@Autowired
private AsyncService asyncService;
調用:
try {
      asyncService.Async(cmdArr);
}catch(Exception e) {
      throw new RuntimeException("業務程序報錯啦!!");
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章