博客
关于我
Spring Boot使用Future以及定义超时
阅读量:179 次
发布时间:2019-02-28

本文共 3002 字,大约阅读时间需要 10 分钟。

Future类型及其在Spring Boot项目中的应用

Future类型概述

Future是一个用于管理和观察具体Runnable或Callable任务执行结果的接口。在Spring Boot项目中,它提供了对异步任务的控制、查询和结果获取能力。通过Future,我们可以检查任务状态、取消任务(如果允许)以及获取最终结果。

Future接口详解

Future接口定义了五种核心方法:

  • cancel(boolean mayInterruptIfRunning)

    用于取消任务。

    • mayInterruptIfRunning参数决定是否允许中断正在执行的任务。
    • 返回值:true表示任务被取消,false表示取消失败。
  • isCancelled()

    检查任务是否被成功取消。

  • isDone()

    检查任务是否已完成。

  • get()

    获取任务结果,方法阻塞直到任务完成。

  • get(long timeout, TimeUnit unit)

    在指定时间内获取任务结果,超时则返回null。

  • Spring Boot项目配置

    新建pom文件

    在项目根目录创建pom.xml,添加必要的Spring Boot和Lombok依赖:

    org.springframework.boot
    spring-boot-starter
    org.springframework.boot
    spring-boot-starter-test
    test
    org.projectlombok
    lombok
    1.16.20
    provided

    新建异步任务

    创建Task类,实现异步任务:

    import org.springframework.scheduling.annotation.Async;
    import org.springframework.scheduling.annotation.AsyncResult;
    import org.springframework.stereotype.Component;
    @Component
    public class Task {
    private static Random random = new Random();
    @Async("taskExecutor")
    public Future
    run() throws Exception {
    long sleep = random.nextInt(10000);
    log.info("开始任务,耗时:" + sleep + "毫秒");
    Thread.sleep(sleep);
    log.info("完成任务");
    return new AsyncResult<>("test");
    }
    }

    任务执行池配置

    Application类中启用异步配置,并设置合适的线程池:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    @Configuration
    @EnableAsync
    public class TaskPoolConfig {
    @Bean("taskExecutor")
    public Executor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(10);
    executor.setMaxPoolSize(20);
    executor.setQueueCapacity(200);
    executor.setKeepAliveSeconds(60);
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    return executor;
    }
    }

    测试类

    编写测试类,验证异步任务的执行:

    import com.didispace.async.Task;
    import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import static org.junit.Assert.*;
    @SpringBootTest
    public class ApplicationTests {
    @Autowired
    private Task task;
    @Test
    public void testFuture() throws Exception {
    Future
    futureResult = task.run();
    String result = futureResult.get(5, TimeUnit.SECONDS);
    assertEquals("test", result);
    }
    }

    测试结果分析

    未超时情况

    • Future.get()在5秒内获取结果,输出"test"。

    超时情况

    • 若任务未在5秒内完成,Future.get()返回null。

    总结

    通过以上配置和实现,可以在Spring Boot项目中高效管理异步任务。Future类型提供了对任务状态的控制和结果的获取,适用于处理I/O密集型任务或资源受限的环境。

    转载地址:http://zqrj.baihongyu.com/

    你可能感兴趣的文章
    Netty源码—4.客户端接入流程一
    查看>>
    Netty源码—4.客户端接入流程二
    查看>>
    Netty源码—5.Pipeline和Handler一
    查看>>
    Netty源码—6.ByteBuf原理二
    查看>>
    Netty源码—7.ByteBuf原理三
    查看>>
    Netty源码—7.ByteBuf原理四
    查看>>
    Netty源码—8.编解码原理二
    查看>>
    Netty源码解读
    查看>>
    Netty的Socket编程详解-搭建服务端与客户端并进行数据传输
    查看>>
    Netty相关
    查看>>
    Network Dissection:Quantifying Interpretability of Deep Visual Representations(深层视觉表征的量化解释)
    查看>>
    Network Sniffer and Connection Analyzer
    查看>>
    NetworkX系列教程(11)-graph和其他数据格式转换
    查看>>
    Networkx读取军械调查-ITN综合传输网络?/读取GML文件
    查看>>
    Net与Flex入门
    查看>>
    net包之IPConn
    查看>>
    NFinal学习笔记 02—NFinalBuild
    查看>>
    NFS共享文件系统搭建
    查看>>
    nfs复习
    查看>>
    NFS网络文件系统
    查看>>