Spring 异步接口返回结果的四种方式

目录
  • 1. 需求
  • 2. 解决方案
    • 2.1 @Async
    • 2.2 TaskExecutor
    • 2.3 Future
    • 2.4 @EventListener
  • 3. 总结

1. 需求

开发中我们经常遇到异步接口需要执行一些耗时的操作,并且接口要有返回结果。

使用场景:用户绑定邮箱、手机号,将邮箱、手机号保存入库后发送邮件或短信通知
接口要求:数据入库后给前台返回成功通知,后台异步执行发邮件、短信通知操作

一般的话在企业中会借用消息队列来实现发送,业务量大的话有一个统一消费、管理的地方。但有时项目中没有引用mq相关组件,这时为了实现一个功能去引用、维护一个消息组件有点大材小用,下面介绍几种不引用消息队列情况下的解决方式

定义线程池:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
 * @description: 公共配置
 * @author: yh
 * @date: 2022/8/26
 */
@EnableAsync
@Configuration
public class CommonConfig {
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置核心线程数
        executor.setCorePoolSize(50);
        // 设置最大线程数
        executor.setMaxPoolSize(200);
        // 设置队列容量
        executor.setQueueCapacity(200);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(800);
        // 设置默认线程名称
        executor.setThreadNamePrefix("task-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

2. 解决方案

2.1 @Async

定义异步任务,如发送邮件、短信等

@Service
public class ExampleServiceImpl implements ExampleService {
    @Async("taskExecutor")
    @Override
    public void sendMail(String email) {
        try {
            Thread.sleep(3000);
            System.out.println("异步任务执行完成, " + email + " 当前线程:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

Controller

@RequestMapping(value = "/api")
@RestController
public class ExampleController {
    @Resource
    private ExampleService exampleService;

    @RequestMapping(value = "/bind",method = RequestMethod.GET)
    public String bind(@RequestParam("email") String email) {
        long startTime = System.currentTimeMillis();
        try {
            // 绑定邮箱....业务
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //模拟异步任务(发邮件通知、短信等)
        exampleService.sendMail(email);

        long endTime = System.currentTimeMillis();
        System.out.println("方法执行完成返回,耗时:" + (endTime - startTime));
        return "ok";
    }
}

运行结果:

2.2 TaskExecutor

@RequestMapping(value = "/api")
@RestController
public class ExampleController {
    @Resource
    private ExampleService exampleService;
    @Resource
    private TaskExecutor taskExecutor;

    @RequestMapping(value = "/bind", method = RequestMethod.GET)
    public String bind(@RequestParam("email") String email) {
        long startTime = System.currentTimeMillis();
        try {
            // 绑定邮箱....业务
            Thread.sleep(2000);

            // 将发送邮件交给线程池去执行
            taskExecutor.execute(() -> {
                exampleService.sendMail(email);
            });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("方法执行完成返回,耗时:" + (endTime - startTime));
        return "ok";
    }
}

运行结果:

2.3 Future

首先去掉Service方法中的@Async("taskExecutor"),此时执行就会变成同步,总计需要5s才能完成接口返回。这次我们使用jdk1.8中的CompletableFuture来实现异步任务

@RequestMapping(value = "/api")
@RestController
public class ExampleController {
    @Resource
    private ExampleService exampleService;
    @Resource
    private TaskExecutor taskExecutor;

    @RequestMapping(value = "/bind", method = RequestMethod.GET)
    public String bind(@RequestParam("email") String email) {
        long startTime = System.currentTimeMillis();
        try {
            // 绑定邮箱....业务
            Thread.sleep(2000);

            // 将发送邮件交给异步任务Future,需要记录返回值用supplyAsync
            CompletableFuture.runAsync(() -> {
                exampleService.sendMail(email);
            }, taskExecutor);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("方法执行完成返回,耗时:" + (endTime - startTime));
        return "ok";
    }
}

运行结果:

2.4 @EventListener

Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式;为的就是业务系统逻辑的解耦,提高可扩展性以及可维护性。事件发布者并不需要考虑谁去监听,监听具体的实现内容是什么,发布者的工作只是为了发布事件而已。

2.4.1 定义event事件模型

public class NoticeEvent extends ApplicationEvent {
    private String email;
    private String phone;
    public NoticeEvent(Object source, String email, String phone) {
        super(source);
        this.email = email;
        this.phone = phone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
}

2.4.2 事件监听

@Component
public class ComplaintEventListener {

    /**
     * 只监听NoticeEvent事件
     * @author: yh
     * @date: 2022/8/27
     */
    @Async
    @EventListener(value = NoticeEvent.class)
//    @Order(1) 指定事件执行顺序
    public void sendEmail(NoticeEvent noticeEvent) {
        //发邮件
        try {
            Thread.sleep(3000);
            System.out.println("发送邮件任务执行完成, " + noticeEvent.getEmail() + " 当前线程:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Async
    @EventListener(value = NoticeEvent.class)
//    @Order(2) 指定事件执行顺序
    public void sendMsg(NoticeEvent noticeEvent) {
        //发短信
        try {
            Thread.sleep(3000);
            System.out.println("发送短信步任务执行完成, " + noticeEvent.getPhone() + " 当前线程:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

2.4.5 事件发布

@RequestMapping(value = "/api")
@RestController
public class ExampleController {
    /**
     * 用于事件推送
     * @author:  yh
     * @date:  2022/8/27
     */
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @RequestMapping(value = "/bind", method = RequestMethod.GET)
    public String bind(@RequestParam("email") String email) {
        long startTime = System.currentTimeMillis();
        try {
            // 绑定邮箱....业务
            Thread.sleep(2000);

            // 发布事件,这里偷个懒手机号写死
            applicationEventPublisher.publishEvent(new NoticeEvent(this, email, "13211112222"));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("方法执行完成返回,耗时:" + (endTime - startTime));
        return "ok";
    }
}

运行结果:

3. 总结

通过@Async、子线程、Future异步任务、Spring自带ApplicationEvent事件监听都可以完成以上描述的需求。

到此这篇关于Spring 异步接口返回结果的四种方式的文章就介绍到这了,更多相关Spring 异步接口内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot利用aop实现接口异步(进度条)的全过程

    目录 一.前言 二.时序图 三.功能演示 四.关键代码 Controller AsyncAop AsyncService 五.源码地址 总结 一.前言 在项目中发现有接口(excel导入数据)处理数据需要耗时比较长的时间,是因为数据量比较大,同时数据的校验需要耗费一定时间,决定使用一种通用的方法解决这个问题. 解决方案:通过aop使接口异步处理,前端轮询另外一个接口查询进度. 目标: 1接口上一个注解即可实现接口异步(优化:可以通过header参数动态控制是否异步) 2一个方法实现进度条的更新

  • Spring Data JPA实现查询结果返回map或自定义的实体类

    目录 Spring Data JPA查询结果返回map或自定义的实体类 1.工具类 2.具体应用 spingboot:jpa:Spring data jpa 返回map 结果集 Spring Data JPA查询结果返回map或自定义的实体类 在JPA中我们可以使用entityManager.createNativeQuery()来执行原生的SQL语句,并且JPA的底层实现都是支持返回Map对象的. 例如: EclipseLink 的 query.setHint(QueryHints.RESUL

  • Springboot jpa使用sum()函数返回结果如何被接收

    目录 jpa使用sum()返回结果如何接收 1.需求 2.解决方法一 3.解决方法二 jpa使用count函数和sum函数 方法一 方法二 方法三 jpa使用sum()返回结果如何接收 1.需求 我的需求是统计域名以及域名出现的次数. 之前使用springboot jpa都是把数据库中的表跟实体类绑定,创建继承JpaRepository的接口.如下: @Repository public interface UrlsRepository extends JpaRepository<Urls, S

  • SpringBoot接口返回结果封装方法实例详解

    rest接口会返回各种各样的数据,如果对接口的格式不加约束,很容易造成混乱. 在实际项目中,一般会把结果放在一个封装类中,封装类中包含http状态值,状态消息,以及实际的数据.这里主要记录两种方式:(效果如下) 1.采用Map对象作为返回对象. /** * Http请求接口结果封装方法 * * @param object 数据对象 * @param msgSuccess 提示信息(请求成功) * @param msgFailed 提示信息(请求失败) * @param isOperate 是否操

  • springboot jpa 实现返回结果自定义查询

    目录 jpa返回结果自定义查询 第一种方法 第二种方法 使用jpa两张表联查返回自定义实体 1.创建一个SpringBoot空白项目,引入pom依赖 2.application.yml配置文件 3.数据库(有两张表user/address) 4.User.java和Address.java 5.UserDaoRepository.java和AddressDaoRepository.java 6.UserAddressDto.java代码 7.TestController.java jpa 返回结

  • 解决SpringBoot返回结果如果为null或空值不显示处理问题

    SpringBoot返回结果如果为null或空值不显示处理 第一种方法:自定义消息转换器 @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter{ // /** // * 利用fastjson替换掉jackson // * @param converters // */ @Override public void configureMessageConverters(List<HttpMessageConv

  • Spring 异步接口返回结果的四种方式

    目录 1. 需求 2. 解决方案 2.1 @Async 2.2 TaskExecutor 2.3 Future 2.4 @EventListener 3. 总结 1. 需求 开发中我们经常遇到异步接口需要执行一些耗时的操作,并且接口要有返回结果. 使用场景:用户绑定邮箱.手机号,将邮箱.手机号保存入库后发送邮件或短信通知接口要求:数据入库后给前台返回成功通知,后台异步执行发邮件.短信通知操作 一般的话在企业中会借用消息队列来实现发送,业务量大的话有一个统一消费.管理的地方.但有时项目中没有引用m

  • Python获取协程返回值的四种方式详解

    目录 介绍 源码 依次执行结果 介绍 获取协程返回值的四种方式: 1.通过ensure_future获取,本质是future对象中的result方 2.使用loop自带的create_task, 获取返回值 3.使用callback, 一旦await地方的内容运行完,就会运行callback 4.使用partial这个模块向callback函数中传入值 源码 import asyncio from functools import partial async def talk(name): pr

  • 详解Spring加载Properties配置文件的四种方式

    一.通过 context:property-placeholder 标签实现配置文件加载 1.用法示例: 在spring.xml配置文件中添加标签 复制代码 代码如下: <context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/> 2.在 spring.xml 中使用配置文件属性: <!-- 基本属性 url.

  • Spring Boot异步线程间数据传递的四种方式

    目录 Spring Boot 自定义线程池实现异步开发 1. 手动设置 2. 线程池设置TaskDecorator 3. InheritableThreadLocal 4. TransmittableThreadLocal TransmittableThreadLocal原理 总结 Spring Boot 自定义线程池实现异步开发 Spring Boot 自定义线程池实现异步开发相信看过的都了解,但是在实际开发中需要在父子线程之间传递一些数据,比如用户信息,链路信息等等 比如用户登录信息使用Th

  • 基于spring三方包类注入容器的四种方式小结

    如果引用第三方jar包,肯定是不能直接使用常用注解@Controller.@Service.@Repository.@Component将类的实例注入到spring容器中.以下四种方法可以向spring容器中导入三方包中类实例 . 1 xml配置 这种情况大家用的比较多,就是在spring的xml文件中配置需要导入的bean.在springweb项目工程web.xml中 ContextLoaderListener或者DispatcherServlet的初始参数contextConfigLocat

  • Spring中集成Groovy的四种方式(小结)

    groovy是一种动态脚本语言,适用于一些可变.和规则配置性的需求,目前Spring提供ScriptSource接口,支持两种类型,一种是 ResourceScriptSource,另一种是 StaticScriptSource,但是有的场景我们需要把groovy代码放进DB中,所以我们需要扩展这个. ResourceScriptSource:在 resources 下面写groovy类 StaticScriptSource:把groovy类代码放进XML里 DatabaseScriptSour

  • Spring中实例化bean的四种方式详解

    前言 在介绍Bean的实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果把Spring看作一个大型工厂,那么Spring容器中的Bean就是该工厂的产品.要想使用Spring工厂生产和管理Bean,就需要在配置文件中指明需要哪些Bean,以及需要使用何种方式将这些Bean装配到一起. Spring容器支持两种格式的配置文件,分别为Properties文件格式和xml文件格式,而在实际的开发当中,最常使用的额是xml文件格式,因此在如下的讲解中,我们以xml文件格

  • Spring实例化bean的四种方式详解

    目录 一.bean实例化——构造方法(常用) 二.bean实例化——静态工厂(了解) 三.bean实例化——实例工厂(了解) 四.bean实例化——FactoryBean(实用) 一.bean实例化——构造方法(常用) bean本质上就是对象,创建bean使用构造方法完成 BookDao接口: public interface BookDao { public void save(); } BookDaoImpl实现类,利用构造方式提供可访问的构造方法,输出相应字符串: import com.i

  • 详解android进行异步更新UI的四种方式

    大家都知道由于性能要求,Android要求只能在UI线程中更新UI,要想在其他线程中更新UI,我大致总结了4种方式,欢迎补充纠正: 使用Handler消息传递机制: 使用AsyncTask异步任务: 使用runOnUiThread(action)方法: 使用Handler的post(Runnabel r)方法: 下面分别使用四种方式来更新一个TextView. 1.使用Handler消息传递机制 package com.example.runonuithreadtest; import andr

  • Android异步更新UI的四种方式

    大家都知道由于性能要求,android要求只能在UI线程中更新UI,要想在其他线程中更新UI,大致有4种方式,下面分别使用四种方式来更新一个TextView. 1.使用Handler消息传递机制 package com.example.runonuithreadtest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.TextView;

随机推荐