这是我参与8月更文挑战的第9天,活动详情查看:8月更文挑战
上篇文章介绍了SpringBoot使用异步(@Async)提升接口效率
下面继续介绍下Service如何异步调用Dao层
调用Dao再次进行异步处理
上篇主要是针对Controller层调用Service层的异步调用,那么如果我们的Service层调用了多个Dao方法,我们如何进行异步优化呢?继续往下看:
- 常规写法:
Dao
@Repository
public class AsyncDao {
public String AsyncDao1() {
long startTime = System.currentTimeMillis();
try {
//模拟耗时
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":AsyncDao1,耗时:" + (endTime - startTime));
return "AsyncDao1";
}
public String AsyncDao2() {
long startTime = System.currentTimeMillis();
try {
//模拟耗时
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":AsyncDao2,耗时:" + (endTime - startTime));
return "AsyncDao2";
}
public String AsyncDao3() {
long startTime = System.currentTimeMillis();
try {
//模拟耗时
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":AsyncDao3,耗时:" + (endTime - startTime));
return "AsyncDao3";
}
}
Service
@Override
@Async
public void testAsync3() {
long startTime = System.currentTimeMillis();
try {
//模拟耗时
Thread.sleep(3000);
asyncDao.AsyncDao1();
asyncDao.AsyncDao2();
asyncDao.AsyncDao3();
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":void testAsync3(),耗时:" + (endTime - startTime));
}
Controller
@GetMapping("testAsync3")
public String testAsync3() throws ExecutionException, InterruptedException {
asyncService.testAsync3();
return "testAsync3--请求成功!";
}
执行效果
可以看到,我们如果进行常规写法来做的话是非常耗时的,因为是同步调用的,都是按顺序进行,下面来看如何进行异步调用:
- 异步调用
Dao层都是一样的写法,我就不重复写了,不是我懒得展示哈!
Service
@Override
@Async
public void testAsync4() throws InterruptedException, ExecutionException {
long startTime = System.currentTimeMillis();
//模拟耗时
Thread.sleep(3000);
//无返回值
Runnable runnable1 = () -> asyncDao.AsyncDao1();
Runnable runnable2 = () -> asyncDao.AsyncDao2();
//有返回值
Callable<String> callable1 = () -> asyncDao.AsyncDao3();
FutureTask<String> stringFutureTask = new FutureTask<>(callable1);
//加入线程池
threadPool.execute(runnable1);
threadPool.execute(runnable2);
threadPool.execute(stringFutureTask);
//获取返回值
stringFutureTask.get();
long endTime = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":void testAsync4(),耗时:" + (endTime - startTime));
}
Controller
@GetMapping("testAsync4")
public String testAsync4() throws ExecutionException, InterruptedException {
asyncService.testAsync4();
return "testAsync4--请求成功!";
}
执行效果
可以看到调用的方法是同步执行的
以上就是本篇全部内容,持续更新