(十八)SpringBoot2.0使用@Async实现异步调用

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/IT_hejinrong/article/details/89337284

一. 项目示例

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

下一篇:(十九)SpringBoot2.0整合拦截器

猜你喜欢

转载自blog.csdn.net/IT_hejinrong/article/details/89337284