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秒后打印到控制台上!
posted @   努力的校长  阅读(690)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示