Springboot:异步业务处理(十二)
说明
当正常业务处理调用一个复杂业务或者耗时较长的请求时,客户等待时间会比较长,造成不好的用户体验,所以这时候需要用的异步处理
构建一个群发邮件的service接口及实现(模拟)
接口: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);
}
}
构建请求controller
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秒后打印到控制台上!
分类:
springboot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用