实现异步的8种方式

news2025/2/23 19:15:39

前言

异步执行对于开发者来说并不陌生,在实际的开发过程中,很多场景多会使用到异步,相比同步执行,异步可以大大缩短请求链路耗时时间,比如:「发送短信、邮件、异步更新等」,这些都是典型的可以通过异步实现的场景

异步的八种实现方式

  • 线程Thread

  • Future

  • 异步框架CompletableFuture

  • Spring注解@Async

  • Spring ApplicationEvent事件

  • 消息队列

  • 第三方异步框架,比如Hutool的ThreadUtil

  • Guava异步

什么是异步?

在同步操作中,我们执行到 「发送短信」 的时候,我们必须等待这个方法彻底执行完才能执行 「赠送积分」 这个操作,如果 「赠送积分」 这个动作执行时间较长,发送短信需要等待,这就是典型的同步场景。

实际上,发送短信和赠送积分没有任何的依赖关系,通过异步,我们可以实现赠送积分发送短信这两个操作能够同时进行,比如:

线程异步

public class AsyncThread extends Thread {

    @Override
    public void run() {
        System.out.println("Current thread name:" + Thread.currentThread().getName() + " Send email success!");
    }

    public static void main(String[] args) {
        AsyncThread asyncThread = new AsyncThread();
        asyncThread.start();
    }
}

当然如果每次都创建一个Thread线程,频繁的创建、销毁,浪费系统资源,我们可以采用线程池:

private ExecutorService executorService = Executors.newCachedThreadPool();

public void fun() {
    executorService.submit(new Runnable() {
        @Override
        public void run() {
            log.info("执行业务逻辑...");
        }
    });
}

可以将业务逻辑封装到RunnableCallable中,交由线程池来执行。

Future异步

@Slf4j
public class FutureManager {

    public String execute() throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(1);
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {

                System.out.println(" --- task start --- ");
                Thread.sleep(3000);
                System.out.println(" --- task finish ---");
                return "this is future execute final result!!!";
            }
        });

        //这里需要返回值时会阻塞主线程
        String result = future.get();
        log.info("Future get result: {}", result);
        return result;
    }

    @SneakyThrows
    public static void main(String[] args) {
        FutureManager manager = new FutureManager();
        manager.execute();
    }
}

输出结果:

 --- task start --- 
 --- task finish ---
 Future get result: this is future execute final result!!!

CompletableFuture实现异步

public class CompletableFutureCompose {

    /**
     * thenAccept子任务和父任务公用同一个线程
     */
    @SneakyThrows
    public static void thenRunAsync() {
        CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread() + " cf1 do something....");
            return 1;
        });
        CompletableFuture<Void> cf2 = cf1.thenRunAsync(() -> {
            System.out.println(Thread.currentThread() + " cf2 do something...");
        });
        //等待任务1执行完成
        System.out.println("cf1结果->" + cf1.get());
        //等待任务2执行完成
        System.out.println("cf2结果->" + cf2.get());
    }

    public static void main(String[] args) {
        thenRunAsync();
    }
}

我们不需要显式使用ExecutorService,CompletableFuture 内部使用了ForkJoinPool来处理异步任务,如果在某些业务场景我们想自定义自己的异步线程池也是可以的。

Spring的@Async异步

自定义异步线程池

/**
 * 线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
@EnableAsync
@Configuration
public class TaskPoolConfig {
    /**
     * 自定义线程池
     *
     **/
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        //返回可用处理器的Java虚拟机的数量 12
        int i = Runtime.getRuntime().availableProcessors();
        System.out.println("系统最大线程数  : " + i);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(16);
        //最大线程数
        executor.setMaxPoolSize(20);
        //配置队列容量,默认值为Integer.MAX_VALUE
        executor.setQueueCapacity(99999);
        //活跃时间
        executor.setKeepAliveSeconds(60);
        //线程名字前缀
        executor.setThreadNamePrefix("asyncServiceExecutor -");
        //设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
        executor.setAwaitTerminationSeconds(60);
        //等待所有的任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

AsyncService

public interface AsyncService {

    MessageResult sendSms(String callPrefix, String mobile, String actionType, String content);

    MessageResult sendEmail(String email, String subject, String content);
}

@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {

    @Autowired
    private IMessageHandler mesageHandler;

    @Override
    @Async("taskExecutor")
    public MessageResult sendSms(String callPrefix, String mobile, String actionType, String content) {
        try {

            Thread.sleep(1000);
            mesageHandler.sendSms(callPrefix, mobile, actionType, content);

        } catch (Exception e) {
            log.error("发送短信异常 -> ", e)
        }
    }
    
    @Override
    @Async("taskExecutor")
    public sendEmail(String email, String subject, String content) {
        try {

            Thread.sleep(1000);
            mesageHandler.sendsendEmail(email, subject, content);

        } catch (Exception e) {
            log.error("发送email异常 -> ", e)
        }
    }
}

在实际项目中, 使用@Async调用线程池,推荐等方式是是使用自定义线程池的模式,不推荐直接使用@Async直接实现异步。

Spring ApplicationEvent事件实现异步

定义事件

public class AsyncSendEmailEvent extends ApplicationEvent {

    /**
     * 邮箱
     **/
    private String email;

   /**
     * 主题
     **/
    private String subject;

    /**
     * 内容
     **/
    private String content;
  
    /**
     * 接收者
     **/
    private String targetUserId;

}

定义事件处理器

@Slf4j
@Component
public class AsyncSendEmailEventHandler implements ApplicationListener<AsyncSendEmailEvent> {

    @Autowired
    private IMessageHandler mesageHandler;
    
    @Async("taskExecutor")
    @Override
    public void onApplicationEvent(AsyncSendEmailEvent event) {
        if (event == null) {
            return;
        }

        String email = event.getEmail();
        String subject = event.getSubject();
        String content = event.getContent();
        String targetUserId = event.getTargetUserId();
        mesageHandler.sendsendEmailSms(email, subject, content, targerUserId);
      }
}

另外,可能有些时候采用ApplicationEvent实现异步的使用,当程序出现异常错误的时候,需要考虑补偿机制,那么这时候可以结合Spring Retry重试来帮助我们避免这种异常造成数据不一致问题。

消息队列

回调事件消息生产者

@Slf4j
@Component
public class CallbackProducer {

    @Autowired
    AmqpTemplate amqpTemplate;

    public void sendCallbackMessage(CallbackDTO allbackDTO, final long delayTimes) {

        log.info("生产者发送消息,callbackDTO,{}", callbackDTO);

        amqpTemplate.convertAndSend(CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getExchange(), CallbackQueueEnum.QUEUE_GENSEE_CALLBACK.getRoutingKey(), JsonMapper.getInstance().toJson(genseeCallbackDTO), new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //给消息设置延迟毫秒值,通过给消息设置x-delay头来设置消息从交换机发送到队列的延迟时间
                message.getMessageProperties().setHeader("x-delay", delayTimes);
                message.getMessageProperties().setCorrelationId(callbackDTO.getSdkId());
                return message;
            }
        });
    }
}

回调事件消息消费者

@Slf4j
@Component
@RabbitListener(queues = "message.callback", containerFactory = "rabbitListenerContainerFactory")
public class CallbackConsumer {

    @Autowired
    private IGlobalUserService globalUserService;

    @RabbitHandler
    public void handle(String json, Channel channel, @Headers Map<String, Object> map) throws Exception {

        if (map.get("error") != null) {
            //否认消息
            channel.basicNack((Long) map.get(AmqpHeaders.DELIVERY_TAG), false, true);
            return;
        }

        try {
        
            CallbackDTO callbackDTO = JsonMapper.getInstance().fromJson(json, CallbackDTO.class);
            //执行业务逻辑
            globalUserService.execute(callbackDTO);
            //消息消息成功手动确认,对应消息确认模式acknowledge-mode: manual
            channel.basicAck((Long) map.get(AmqpHeaders.DELIVERY_TAG), false);

        } catch (Exception e) {
            log.error("回调失败 -> {}", e);
        }
    }
}

ThreadUtil异步工具类

@Slf4j
public class ThreadUtils {

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            ThreadUtil.execAsync(() -> {
                ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
                int number = threadLocalRandom.nextInt(20) + 1;
                System.out.println(number);
            });
            log.info("当前第:" + i + "个线程");
        }

        log.info("task finish!");
    }
}

Guava异步

GuavaListenableFuture顾名思义就是可以监听的Future,是对java原生Future的扩展增强。我们知道Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果我们希望一旦计算完成就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做,代码复杂,而且效率低下。使用「Guava ListenableFuture」可以帮我们检测Future是否完成了,不需要再通过get()方法苦苦等待异步的计算结果,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。

ListenableFuture是一个接口,它从jdkFuture接口继承,添加了void addListener(Runnable listener, Executor executor)方法。

我们看下如何使用ListenableFuture。首先需要定义ListenableFuture的实例:

Guava的ListenableFuture顾名思义就是可以监听的Future,是对java原生Future的扩展增强。我们知道Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果我们希望一旦计算完成就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做,代码复杂,而且效率低下。使用「Guava ListenableFuture」可以帮我们检测Future是否完成了,不需要再通过get()方法苦苦等待异步的计算结果,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。
ListenableFuture是一个接口,它从jdk的Future接口继承,添加了void addListener(Runnable listener, Executor executor)方法。
我们看下如何使用ListenableFuture。首先需要定义ListenableFuture的实例:

首先通过MoreExecutors类的静态方法listeningDecorator方法初始化一个ListeningExecutorService的方法,然后使用此实例的submit方法即可初始化ListenableFuture对象。

ListenableFuture要做的工作,在Callable接口的实现类中定义,这里只是休眠了1秒钟然后返回一个数字1,有了ListenableFuture实例,可以执行此Future并执行Future完成之后的回调函数。

 Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
    @Override
    public void onSuccess(Integer result) {
        //成功执行...
        System.out.println("Get listenable future's result with callback " + result);
    }

    @Override
    public void onFailure(Throwable t) {
        //异常情况处理...
        t.printStackTrace();
    }
});

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/405916.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Switch语句用法及案例

​ 一、Switch语句用法 switch是多分支语句&#xff0c;用于判断一个表达式的值&#xff0c;然后执行相应的语句。&#xff08;可以实现多选一&#xff09; switch语句执行思路&#xff1a;利用表达式的值&#xff0c;来判断执行哪个语句。&#xff08;简单的来说就是利用我们…

Vue 3 安装及环境配置

Vue 3 安装及环境配置1、安装 Node.js2、配置默认安装目录和缓存日志目录3、配置环境变量4、配置淘宝镜像5、安装 vue 和脚手架6、安装vue-cli 3.x7、创建 vue 3 项目8、可能遇到的问题1、安装 Node.js Node.js 官网&#xff1a;https://nodejs.org/en/download 安装成功后在…

Vue项目实战——实现一个任务清单【基于 Vue3.x 全家桶(简易版)】

Vue3.x 项目实战&#xff08;一&#xff09; 内容参考链接Vue2.x全家桶Vue2.x 全家桶参考链接Vue2.x项目&#xff08;一&#xff09;Vue2.x 实现一个任务清单Vue2.x项目&#xff08;二&#xff09;Vue2.x 实现GitHub搜索案例Vue3.x项目&#xff08;三&#xff09;Vue3.x 实现一…

Vue项目部署(Nginx)

本文记录如何将做好的Vue项目部署到服务器上&#xff0c;需要准备&#xff1a; linux系统的服务器或者虚拟机Vue项目打包Nginx服务器的配置和部署1、linux系统准备 本次使用云主机作为部署主机。 2、Vue项目打包 切换到项目所在目录&#xff0c;使用 npm run build 命令完成项目…

深度学习——VGG16模型详解

1、网络结构 VGG16模型很好的适用于分类和定位任务&#xff0c;其名称来自牛津大学几何组&#xff08;Visual Geometry Group&#xff09;的缩写。 根据卷积核的大小核卷积层数&#xff0c;VGG共有6种配置&#xff0c;分别为A、A-LRN、B、C、D、E&#xff0c;其中D和E两种是最…

yolov5源码解析(9)--输出

本文章基于yolov5-6.2版本。主要讲解的是yolov5是怎么在最终的特征图上得出物体边框、置信度、物体分类的。 一。总体框架 首先贴出总体框架&#xff0c;直接就拿官方文档的图了&#xff0c;本文就是接着右侧的那三层输出开始讨论。 Backbone: New CSP-Darknet53Neck: SPPF, …

JavaWeb酒店管理系统

酒店管理系统 一、项目介绍 1、项目用到的技术栈 开发工具&#xff1a;idea语言&#xff1a;java、js、htmlajax数据库&#xff1a;MySQL服务器&#xff1a;Tomcat框架&#xff1a;mybatis、jQuery 2、项目实现功能 管理员和用户登录和退出功能以及用户注册功能&#xf…

【第二趴】uni-app开发工具(手把手带你安装HBuilderX、搭建第一个多端项目初体验)

文章目录写在前面HBuilderXHBuilderX 优势HBuilderX 安装uni-app 初体验写在最后写在前面 聚沙成塔——每天进步一点点&#xff0c;大家好我是几何心凉&#xff0c;不难发现越来越多的前端招聘JD中都加入了uni-app 这一项&#xff0c;它也已经成为前端开发者不可或缺的一项技能…

Eolink 治愈了后端开发者的痛

一、前后端的爱恨情仇 最近公司的一个前端同事和一个后端同事吵了一架&#xff0c;事情大概是这样的。后端说要联调接口&#xff0c;前端说你的数据尽量按我的要求来&#xff0c;后端不干&#xff0c;说你这个没用。前端就讲道理呀&#xff0c;传统的前后端分离返回的格式要尽…

【node进阶】深入浅出websocket即时通讯(二)-实现简易的群聊私聊

✅ 作者简介&#xff1a;一名普通本科大三的学生&#xff0c;致力于提高前端开发能力 ✨ 个人主页&#xff1a;前端小白在前进的主页 &#x1f525; 系列专栏 &#xff1a; node.js学习专栏 ⭐️ 个人社区 : 个人交流社区 &#x1f340; 学习格言: ☀️ 打不倒你的会使你更强&a…

保姆级教程:Ant Design Vue中 a-table 嵌套子表格

前端为Ant Design Vue 版本为1.6.2&#xff0c;使用的是vue2 Ant Design Vue中 a-table 嵌套子表格&#xff0c;说的可能稍微墨迹了点&#xff0c;不过重点内容都说的比较详细&#xff0c;利于新人理解&#xff0c;高手可以自取完整代码 内容概述&#xff1a;完成样式及完整代…

在收到消息后秒级使网站变灰,不改代码不上线,如何实现?

注意&#xff1a;文本不是讲如何将网站置灰的那个技术点&#xff0c;那个技术点之前汶川地震的时候说过。 本文不讲如何实现技术&#xff0c;而是讲如何在第一时间知道消息后&#xff0c;更快速的实现这个置灰需求的上线。 实现需求不是乐趣&#xff0c;指挥别人去实现需求才…

[Vue warn]: Error in render: “TypeError: Cannot read properties of undefined(reading“category1Name“

明明页面正常显示&#xff0c;但是控制台却一直报 如下 错误 [Vue warn]:渲染错误:"TypeError:无法读取未定义的属性(读取category1Name)" 中发现的 Detail 的 vuex 仓库 import { reqDetail } from "/api" export default{actions:{async getDetail({co…

【前端修炼场】 — 这些标签你学会了么?快速拿下 “hr”

此文为【前端修炼场】第四篇&#xff0c;上一篇文章链接&#xff1a;上一篇 文章目录前言一、 常用标识符1.1 特殊标识符1.1.1 "<" 和 ">"&#xff08;<&#xff1b;&#xff09;1.1.2 空格&#xff08;&emsp&#xff1b;&#xff09;1.1.3 商…

uniapp微信小程序无法使用本地静态资源图片,背景图在真机不显示方法

前言 首先要说明&#xff0c;使用HBuilder或者vs Code工具开发的时候&#xff0c;在微信开发者工具调试的时候&#xff0c;我们使用本地图片是OK的&#xff0c;但是一旦放到真机上调试的时候&#xff0c;图片就显示不出来。 先看uniapp官网对背景图片的说明 错误用法 <tem…

uniapp 微信小程序和H5的弹窗滚动穿透解决

滚动穿透&#xff1a; 页面里的弹窗也是可以滚动的&#xff0c;然后页面本身内容多所以也是滚动的&#xff0c;就造成&#xff0c;在弹窗滚动的时候&#xff0c;页面内容也跟着滚动了。如图所示 ps: 电脑端分鼠标滚轮滚动和长按鼠标拖拽滚动&#xff0c;手机端只有触屏滑屏滚…

视频实时行为检测——基于yolov5+deepsort+slowfast算法

文章目录前言一、核心功能设计二、核心实现步骤1.yolov5实现目标检测2.deepsort实现目标跟踪3.slowfast动作识别三、核心代码解析1.参数2.主函数3.将结果保存成视频总结前言 前段时间打算做一个目标行为检测的项目&#xff0c;翻阅了大量资料&#xff0c;也借鉴了不少项目&…

【Java】运算符

我不去想是否能够成功 既然选择了远方 便只顾风雨兼程 —— 汪国真 目录 1. 认识运算符 1.1 认识运算符 1.2 运算符的分类 2. 算术运算符 2.1 四则运算符 2.2 复合赋值运算符 2.3 自增 / 自减 运算符 3.关系运算符 4.逻辑运算符 4.1 逻辑与 && 4.2 逻…

什么是异步

文章目录 前言一、异步是什么&#xff1f;二、举个例子来理解异步 1.异步最典型的例子就是“回调函数”总结前言 在vue的过程中&#xff0c;我们一定会遇到诸如&#xff1a; function&#xff08;参数&#xff09;.then(res>{}) 形式的代码。到底怎么编译执行的呢 &#xf…

【Jetpack】ViewModel 架构组件 ( 视图 View 和 数据模型 Model | ViewModel 作用 | ViewModel 生命周期 | 代码示例 | 使用注意事项 )

文章目录一、Activity 遇到的问题二、视图 View 和 数据模型 Model三、ViewModel 架构组件作用四、ViewModel 代码示例1、ViewModel 视图模型2、Activity 组件3、UI 布局文件4、运行效果五、ViewModel 生命周期六、ViewModel 使用注意事项一、Activity 遇到的问题 Activity 遇到…