一. 项目示例
1.1 pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
其实该异步实现类spring已经有了,直接调用即可。
1.2 启动类加上@EnableAsync
@EnableAsync
@SpringBootApplication
public class Springboot210Application {
public static void main(String[] args) {
SpringApplication.run(Springboot210Application.class, args);
}
}
1.3 需要执行异步方法上加@Async
我在更新用户的方法上加上@Async注解,模拟更新用户会员信息及投资金额,这时就不用等待updateIndexBb方法执行完,就可以直接返回结果,页面无需等待。
我在updateUserInfo方法上加了@Async,表示该方法会另外开启一个线程去执行,同时我也异步去更新VIP用户信息和用户投资金额,所以我在其他两个方法上也加上了@Async,这个一般看情况而定。
@Async
@Override
public void updateVipInfo(String userId) {
log.info("【查询VIP用户信息开始】,参数:[userId:{}]", userId);
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("【查询VIP用户信息结束】,参数:[userId:{}]", userId);
}
@Async
@Override
public void updateUserMoney(String userId) {
log.info("【查询用户投资金额开始】,参数:[userId:{}]", userId);
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("【查询用户投资金额开始】,参数:[userId:{}]", userId);
}
@Async
@Override
public void updateUserInfo(String userId) {
log.info("【更新用户信息开始】,参数:[userId:{}]", userId);
try {
updateVipInfo(userId);
updateUserMoney(userId);
} catch (Exception e) {
e.printStackTrace();
}
log.info("【更新用户信息结束】,参数:[userId:{}]", userId);
}
1.4 演示
在浏览器中输入地址:http://localhost:8080/index/updateUserInfo?userId=hejinrong
即可看到返回的结果:
日志打印如下:
二. 源码下载
https://gitee.com/hejr.cn.com/SpringBoot2.0_2019/tree/master/springboot2_10