Spring注解 @Async 实现异步调用方法
异步方法调用使用场景:处理日志、发送邮件、发送短信。。。
关于@Async:
(1)Spring 3.0 以及以后版本中支持的@Async
(2)@Async修饰类,则该类所有方法都是异步的,@Async修饰方法,则该方法是异步的。
(3)只有@Async注解修饰的方法还不能够生效,还需要在SpringBoot的主程序Application中或对应的类上配置注解@EnableAsync才能够生效。
(4)@Async所修饰的函数不要定义为static类型,这样异步调用不会生效。
此Demo是模拟发邮件,我们网站的后台,给邮件服务器发送验证码让他发送到指定邮箱。然后立即通知用户,验证码已发送。不用等待邮件服务器完成后,才通知用户验证码已发送。假如邮件服务器给指定邮箱发送验证码失败,再通知用户,请重新获取验证码。
主程序Application
package com.example.springBootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
/**
*
* @author luolei
* @date 2018年10月28日
*/
@SpringBootApplication
@EnableAsync //开启异步
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
controller
package com.example.springBootdemo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.springBootdemo.service.impl.SendValidCodeServiceImpl;
/**
*
* @author luolei
* @date 2019年1月30日
*/
@RestController
/*@Controller
@ResponseBody*/
//@EnableAsync //开启异步
@RequestMapping("/sendValidCode")
public class SendValidCodeController {
@Autowired
private SendValidCodeServiceImpl sendValidCodeService;
@GetMapping("/send")
//@RequestMapping("/send")
public String SendValidCode() throws InterruptedException {
System.out.println("1、后台服务器向邮件服务器请求:给XXX发送验证码...");
sendValidCodeService.sendValidCode();
sendValidCodeService.sendMesssage();
return "success";
}
}
service
package com.example.springBootdemo.service.impl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class SendValidCodeServiceImpl {
@Async
public void sendValidCode() throws InterruptedException{
Thread.sleep(3000);
System.out.println("2、邮件服务器操作:将验证码发送到XXX...");
}
@Async
public void sendMesssage() throws InterruptedException{
System.out.println("3、后台服务器提示用户:验证码已发送...");
}
}
效果
还没有评论,来说两句吧...