SpringBoot学习之路---记录异步任务(@Async注解)

我们在开发中,往往会碰到和多线程相关的问题。我们有时往往需要异步去解决问题,SpringBoot为我们提供了一个注解,接下来记录一下。


这里假设有一个情景,编写一个service层的代码,需要等待3秒的时间,如果是同步的代码的话,在此过程中,用户只能等待3秒,期间什么事都不能做,不管对于系统还是用户来说,都是不好的。系统那段时间没有做事,会浪费时间,而用户等待过程中用户体验也不是很好。

这里先编写一个小demo代码:

service:

@Service
public class HelloService {

    public void hello(){

        try {
            Thread.sleep(3000);
            System.out.println("处理数据...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

这个代码作用也是比较简单,就是在让系统"沉睡"3秒。接着在写一个controller去调用它:

controller:

@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @GetMapping("hello")
    public String hello(){
        String hello = helloService.hello();

        return "hello world";
    }
}

我们在浏览器访问该路径时,需要等待3秒才可以有结果。这就会像我们上文提到的一样,我们这时就会想到用异步的方式去解决它,如果自己编写异步代码那挺麻烦的(当时学多线程的噩梦…),好在SpringBoot为我们提供了一个注解(@Async),我们只需要把该注解标注在需要的方法即可。

@Async

之后,还差一步,我们是标注了异步注解,但是还要去开启异步的相关支持,需要在主启动类中添加

#EnableAsync //表示开启异步的相关支持

之后再次访问路径,就无需等待,便可直接访问:
在这里插入图片描述
这个注解平时应用场景挺多的,比如给用户发送邮件,推送消息等等。就无需一步一步做了,可以同时执行。

猜你喜欢

转载自blog.csdn.net/Jokeronee/article/details/105882803