当正常业务处理调用一个复杂业务或者耗时较长的请求时,客户等待时间会比较长,造成不好的用户体验,所以这时候需要用的异步处理
接口:com\springboot\service\AsynxService.java
package com.applesnt.springboot.service;
public interface AsynxService {
/*群发邮件*/
public void sendMail();
}
实现类:com\applesnt\springboot\service\impl\AsynxServiceImpl.java
需要异步业务处理的方法使用@Async注解
package com.applesnt.springboot.service.impl;
import com.applesnt.springboot.service.AsynxService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsynxServiceImpl implements AsynxService {
@Override
@Async/*异步调用 需要在启动类中开启异步支持*/
public void sendMail() {
try {
/*模拟群发邮件耗时 5秒*/
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("邮件发送完成");
}
}
开启异步注解支持:@EnableAsync
package com.applesnt.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync/*开启异步支持*/
@SpringBootApplication
public class SpringbootTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTestApplication.class, args);
}
}
com\applesnt\springboot\controller\AsynxController.java
package com.applesnt.springboot.controller;
import com.applesnt.springboot.service.AsynxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class AsynxController {
@Autowired
AsynxService asynxService;
@RequestMapping("/sendmail")
@ResponseBody
public String sendMail(){
/*
* 调用模拟发送邮件的功能,如果不做异步 客户会等待很长时间
* 使用了异步,会直接返回结果,而发送邮件的业务方法会单独去执行
* */
asynxService.sendMail();
return "异步处理 发送完成";
}
}
当浏览器发出http://localhost/senmail的请求后,浏览器会立刻打印出controller返回的信息;在service中调用的方法会在5秒后打印到控制台上!
原文:https://www.cnblogs.com/applesnt/p/12727750.html