前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot使用异步任务

springboot使用异步任务

作者头像
阿超
发布2022-08-16 17:23:15
3840
发布2022-08-16 17:23:15
举报
文章被收录于专栏:快乐阿超

一个简单的异步任务在springboot中已经为我们封装好,这里我们可以直接在函数上加@Async注解即可使用

注意,我们要接收返回值的话,函数返回类型需要为Future

例如,我们这里使用异步任务和建造者模式去创建一个对象

代码语言:javascript
复制
package com.ruben;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @ClassName: AsyncDemo
 * @Description: 我还没有写描述
 * @Date: 2020/11/30 0030 21:17
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
@SpringBootTest
public class AsyncDemo {

    @Test
    public void test() throws ExecutionException, InterruptedException {
        Future<StreamDemo.User> future = whoAmI("ruben", 19);
        StreamDemo.User user = future.get();
        System.out.println(user);
    }

    @Async
    public Future<StreamDemo.User> whoAmI(String ruben, Integer age) {
        return new AsyncResult<>(StreamDemo.User.builder().name(ruben).age(age).build());
    }

}

运行结果

image-20201130212928922
image-20201130212928922

要注意这里返回值是new AsyncResult

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-11-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档