目前就只学了一种方法,看了很多,能看明白的好少,自己总结一下:
导包:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
类1:写正常逻辑,含异步方法的调用
@Autowired
private AsynTask asynTask;
public void getActions() throws ExecutionException, InterruptedException, TimeoutException {
//实现异步调用
Future future = asynTask.springAsynchronousMethod();
//该写法是当前类的调用,不会实现异步
//Future future = springAsynchronousMethod();
System.out.println(111);
JSONObject o = (JSONObject)future.get(1000, TimeUnit.MILLISECONDS);
log.info("结果:{}", JSON.toJSONString(o));
}
类2:写异步方法
@Async
public Future springAsynchronousMethod(){
JSONObject testData = testService.getTestData(1000550L, ApiAspect.getCurrentUser());
return new AsyncResult(testData);
}
此处我特意使用System.out.println(111);来看控制台,异步方法是否生效:
如果先打印111,再出现reponse结果,则实现异步;否则,是同步。
note: 使用注解@Async,必须在主类MamsNexusApplication中写入@EnableAsync,来使得注解@Async生效