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、后台服务器提示用户:验证码已发送...");
	}

}

效果

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值