github project Address: https://github.com/lgsdaredevil/asyncTest
Open asynchronous tasks
Add @EnableAsync notes in the application main class
Write asynchronous task methods
@Async
public Future<String> ansync(String name){
try {
Thread.sleep(10000);
logger.info("这里是异步方法");
logger.info("传过来的名字是:" + name);
name = "修改的名字";
logger.info("修改后的名字是:" + name);
return new AsyncResult<>("name: " + name);
}catch (Exception e){
return new AsyncResult<>("异常");
}
}
Asynchronous method call
- 1, by acquiring the return value Future
public String requestAnsync(String name){
try {
Long start = System.currentTimeMillis();
Future<String> result = ansync(name);
if (result.isDone()){
name = result.get();
logger.info("异步方法结束,名字改为:" + name);
}
Long end = System.currentTimeMillis();
logger.info("耗时:" + (int)(end-start));
return "hello " + name;
}catch (Exception e){
logger.error("异常");
return "异常";
}
}
If you want to get a return value, you should get the polling method, otherwise it will not go Ruoguo no isDone the following methods, or you can use CompletableFuture:
2018-07-17 11:31:55.390 INFO 5232 --- [nio-8080-exec-6] c.e.async.service.AsyncTestService : 耗时:0
2018-07-17 11:32:05.394 INFO 5232 --- [cTaskExecutor-3] com.example.async.service.AsyncTest : 这里是异步方法
2018-07-17 11:32:05.394 INFO 5232 --- [cTaskExecutor-3] com.example.async.service.AsyncTest : 传过来的名字是:ling
2018-07-17 11:32:05.394 INFO 5232 --- [cTaskExecutor-3] com.example.async.service.AsyncTest : 修改后的名字是:修改的名字
If you use future.get () method blocks the thread until I got the results.
- 2, do not use Future.get () method, asynchronous method is not used to return Future
@Async
public void noReturnAsync(String name){
try {
Thread.sleep(10000);
logger.info("这里是异步方法");
logger.info("传过来的名字是:" + name);
name = "修改的名字";
logger.info("修改后的名字是:" + name);
}catch (Exception e){
}
}
Asynchronous method call
public String noReturn(String name){
Long start = System.currentTimeMillis();
asyncTest.noReturnAsync(name);
Long end = System.currentTimeMillis();
logger.info("耗时:" + (int)(end-start));
return "hello " + name;
}
Note specific region:
If the asynchronous method to synchronous method blocks, possibly because of the asynchronous method calls and ordinary methods in the same class, the solution is an asynchronous method into a separate class.
Reason: When spring when @Transactional for annotation have similar problems, have @Transactional annotation classes when spring scanning method, is to generate a proxy class by proxy class to open and close the transaction, while in the same class, method calls in , spring can not intercept the call to execute the method of the class body.
Referring specifically: the Spring @Async asynchronous call using the Boot