烟台定制网站建设报价sem搜索
一、使用@Async实现异步调用
在Spring Boot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步函数,Task类实现如下:
package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;import java.util.Random;
import java.util.concurrent.CompletableFuture;@Slf4j
@Component
public class AsyncTasks {public static Random random = new Random();@Asyncpublic CompletableFuture<String> doTaskOne() throws Exception {log.info("开始做任务一");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务一,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务一完成");}@Asyncpublic CompletableFuture<String> doTaskTwo() throws Exception {log.info("开始做任务二");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务二,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务二完成");}@Asyncpublic CompletableFuture<String> doTaskThree() throws Exception {log.info("开始做任务三");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务三,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务三完成");}
}
注:@Async所修饰的函数不要定义为static类型,这样异步调用不会生效
为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync,如下所示:
package com.example.demospringboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;@EnableAsync
@SpringBootApplication
public class DemospringbootApplication {public static void main(String[] args) {SpringApplication.run(DemospringbootApplication.class, args);}}
测试类如下:
package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.cache.CacheManager;@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemospringbootApplicationTests {@Autowiredprivate AsyncTasks asyncTasks;@Testpublic void test() throws Exception {asyncTasks.doTaskOne();asyncTasks.doTaskTwo();asyncTasks.doTaskThree();}}
此时可以反复执行单元测试,您可能会遇到各种不同的结果,比如:
2023-08-01 21:32:46.064 INFO 1764 --- [ task-1] com.example.demospringboot.AsyncTasks : 开始做任务一
2023-08-01 21:32:46.064 INFO 1764 --- [ task-3] com.example.demospringboot.AsyncTasks : 开始做任务三
2023-08-01 21:32:46.064 INFO 1764 --- [ task-2] com.example.demospringboot.AsyncTasks : 开始做任务二
异步回调
那么我们如何判断上述三个异步调用是否已经执行完成呢?我们需要使用CompletableFuture来返回异步调用的结果,就像如下方式改造doTaskOne函数:
package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;import java.util.Random;
import java.util.concurrent.CompletableFuture;@Slf4j
@Component
public class AsyncTasks {public static Random random = new Random();@Asyncpublic CompletableFuture<String> doTaskOne() throws Exception {log.info("开始做任务一");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务一,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务一完成");}@Asyncpublic CompletableFuture<String> doTaskTwo() throws Exception {log.info("开始做任务二");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务二,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务二完成");}@Asyncpublic CompletableFuture<String> doTaskThree() throws Exception {log.info("开始做任务三");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务三,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务三完成");}}
下面我们改造一下测试用例,让测试在等待完成三个异步调用之后来做一些其他事情
package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CompletableFuture;@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemospringbootApplicationTests {@Autowiredprivate AsyncTasks asyncTasks;@Testpublic void test() throws Exception {long start = System.currentTimeMillis();CompletableFuture<String> task1 = asyncTasks.doTaskOne();CompletableFuture<String> task2 = asyncTasks.doTaskTwo();CompletableFuture<String> task3 = asyncTasks.doTaskThree();CompletableFuture.allOf(task1, task2, task3).join();long end = System.currentTimeMillis();log.info("任务全部完成,总耗时:" + (end - start) + "毫秒");}}
执行一下上述的单元测试,可以看到如下结果:
2023-08-01 21:41:40.347 INFO 13684 --- [ task-1] com.example.demospringboot.AsyncTasks : 开始做任务一
2023-08-01 21:41:40.347 INFO 13684 --- [ task-3] com.example.demospringboot.AsyncTasks : 开始做任务三
2023-08-01 21:41:40.347 INFO 13684 --- [ task-2] com.example.demospringboot.AsyncTasks : 开始做任务二
2023-08-01 21:41:44.817 INFO 13684 --- [ task-2] com.example.demospringboot.AsyncTasks : 完成任务二,耗时:4470毫秒
2023-08-01 21:41:45.042 INFO 13684 --- [ task-1] com.example.demospringboot.AsyncTasks : 完成任务一,耗时:4695毫秒
2023-08-01 21:41:48.154 INFO 13684 --- [ task-3] com.example.demospringboot.AsyncTasks : 完成任务三,耗时:7807毫秒
2023-08-01 21:41:48.154 INFO 13684 --- [ main] c.e.d.DemospringbootApplicationTests : 任务全部完成,总耗时:7817毫秒
可以看到,通过异步调用,让任务一、二、三并发执行,有效的减少了程序的总运行时间。
参考:https://blog.didispace.com/spring-boot-learning-2-7-5/