Spring注解 @Async 实现异步调用方法

朱雀 2020-10-17 15:30 992阅读 0赞

异步方法调用使用场景:处理日志、发送邮件、发送短信。。。

关于@Async:

(1)Spring 3.0 以及以后版本中支持的@Async

(2)@Async修饰类,则该类所有方法都是异步的,@Async修饰方法,则该方法是异步的。

(3)只有@Async注解修饰的方法还不能够生效,还需要在SpringBoot的主程序Application中或对应的类上配置注解@EnableAsync才能够生效。

(4)@Async所修饰的函数不要定义为static类型,这样异步调用不会生效。


此Demo是模拟发邮件,我们网站的后台,给邮件服务器发送验证码让他发送到指定邮箱。然后立即通知用户,验证码已发送。不用等待邮件服务器完成后,才通知用户验证码已发送。假如邮件服务器给指定邮箱发送验证码失败,再通知用户,请重新获取验证码。

主程序Application

  1. package com.example.springBootdemo;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.scheduling.annotation.EnableAsync;
  5. /**
  6. *
  7. * @author luolei
  8. * @date 2018年10月28日
  9. */
  10. @SpringBootApplication
  11. @EnableAsync //开启异步
  12. public class SpringBootDemoApplication {
  13. public static void main(String[] args) {
  14. SpringApplication.run(SpringBootDemoApplication.class, args);
  15. }
  16. }

controller

  1. package com.example.springBootdemo.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.scheduling.annotation.EnableAsync;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import com.example.springBootdemo.service.impl.SendValidCodeServiceImpl;
  10. /**
  11. *
  12. * @author luolei
  13. * @date 2019年1月30日
  14. */
  15. @RestController
  16. /*@Controller
  17. @ResponseBody*/
  18. //@EnableAsync //开启异步
  19. @RequestMapping("/sendValidCode")
  20. public class SendValidCodeController {
  21. @Autowired
  22. private SendValidCodeServiceImpl sendValidCodeService;
  23. @GetMapping("/send")
  24. //@RequestMapping("/send")
  25. public String SendValidCode() throws InterruptedException {
  26. System.out.println("1、后台服务器向邮件服务器请求:给XXX发送验证码...");
  27. sendValidCodeService.sendValidCode();
  28. sendValidCodeService.sendMesssage();
  29. return "success";
  30. }
  31. }

service

  1. package com.example.springBootdemo.service.impl;
  2. import org.springframework.scheduling.annotation.Async;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class SendValidCodeServiceImpl {
  6. @Async
  7. public void sendValidCode() throws InterruptedException{
  8. Thread.sleep(3000);
  9. System.out.println("2、邮件服务器操作:将验证码发送到XXX...");
  10. }
  11. @Async
  12. public void sendMesssage() throws InterruptedException{
  13. System.out.println("3、后台服务器提示用户:验证码已发送...");
  14. }
  15. }

效果

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NzZG5sdW9sZWk_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,992人围观)

还没有评论,来说两句吧...

相关阅读