SpringBoot系列 - 异步线程池

在项目中,当访问其他人的接口较慢或者做耗时任务时,不想程序一直卡在耗时任务上,想程序能够并行执行, 我们可以使用多线程来并行的处理任务,也可以使用spring提供的异步处理方式@Async。

Spring异步线程池的接口类,其实质是java.util.concurrent.Executor。

Spring 已经实现的异常线程池:

SimpleAsyncTaskExecutor:不是真的线程池,这个类不重用线程,每次调用都会创建一个新的线程。
SyncTaskExecutor:这个类没有实现异步调用,只是一个同步操作,只适用于不需要多线程的地方
ConcurrentTaskExecutor:Executor的适配类,不推荐使用。如果ThreadPoolTaskExecutor不满足要求时,才用考虑使用这个类
SimpleThreadPoolTaskExecutor:是Quartz的SimpleThreadPool的类。线程池同时被quartz和非quartz使用,才需要使用此类
ThreadPoolTaskExecutor:最常使用,推荐。其实质是对java.util.concurrent.ThreadPoolExecutor的包装
在异步处理的方法上添加注解@Async,就会启动一个新的线程去执行。

开启异步配置
SpringBoot中开启异步支持非常简单,只需要在配置类上面加上注解@EnableAsync,同时定义自己的线程池即可。 也可以不定义自己的线程池,则使用系统默认的线程池。这个注解可以放在Application启动类上,但是更推荐放在配置类上面。

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    // 省略...
}

异步处理方法分为不返回结果和返回结果,这两者的处理是有区别的。

返回void
没有结果返回的示例:

@Component
public class AsyncTask {
    @Async
    public void dealNoReturnTask(){
        log.info("返回值为void的异步调用开始" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("返回值为void的异步调用结束" + Thread.currentThread().getName());
    }
}

返回Future
异步调用返回数据,Future表示在未来某个点获取执行结果,返回数据类型可以自定义

@Async
public Future<String> dealHaveReturnTask(int i) {
    log.info("asyncInvokeReturnFuture, parementer=" + i);
    Future<String> future;
    try {
        Thread.sleep(1000 * i);
        future = new AsyncResult<String>("success:" + i);
    } catch (InterruptedException e) {
        future = new AsyncResult<String>("error");
    }
    return future;
}

以上的异步方法和普通的方法调用相同:

Future<String> future = asyncDemo.asyncInvokeReturnFuture(100);
System.out.println(future.get());

异常处理
我们可以实现AsyncConfigurer接口,也可以继承AsyncConfigurerSupport类来实现。

在方法getAsyncExecutor()中创建线程池的时候,必须使用 executor.initialize(),不然在调用时会报线程池未初始化的异常。


@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60 * 10);
        executor.setThreadNamePrefix("AsyncThread-");
        executor.initialize(); //如果不初始化,导致找到不到执行器
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }
}

异步异常处理类:

public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(AsyncExceptionHandler.class);
    
    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        log.info("Async method has uncaught exception, params: " + params);

        if (ex instanceof AsyncException) {
            AsyncException asyncException = (AsyncException) ex;
            log.info("asyncException:"  + asyncException.getMsg());
        }

        log.error("Exception :", ex);
    }
}

异步处理异常类:

public class AsyncException extends Exception {
    private int code;
    private String msg;
    
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

在调用方法时,可能出现方法中抛出异常的情况。Spring对于2种异步方法的异常处理机制如下:

对于方法返回值是Futrue的异步方法: a) 在调用future的get时捕获异常; b) 在异常方法中直接捕获异常
对于返回值是void的异步方法:通过AsyncUncaughtExceptionHandler处理异常
测试代码
最后写个测试代码看看是否跟预期一致:



/**
 * 测试异步任务
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    private static final Logger log = LoggerFactory.getLogger(ApplicationTests.class);
    @Autowired
    private AsyncTask asyncTask;

    @Test
    public void testAsync() throws InterruptedException, ExecutionException {
        asyncTask.dealNoReturnTask();

        Future<String> f = asyncTask.dealHaveReturnTask(5);

        log.info("主线程执行finished");

        log.info(f.get());
        assertThat(f.get(), is("success:" + 5));
    }
}

执行日志如下:

INFO 4180 — [ main] com.xncoding.pos.ApplicationTests : 主线程执行finished
INFO 4180 — [ AsyncThread-2] com.xncoding.pos.async.AsyncTask : asyncInvokeReturnFuture, parementer=5
INFO 4180 — [ AsyncThread-1] com.xncoding.pos.async.AsyncTask : 返回值为void的异步调用开始AsyncThread-1
INFO 4180 — [ AsyncThread-1] com.xncoding.pos.async.AsyncTask : 返回值为void的异步调用结束AsyncThread-1
INFO 4180 — [ main] com.xncoding.pos.ApplicationTests : success:5
INFO 4180 — [ Thread-4] o.s.w.c.s.GenericWebApplicationContext : Closing …
INFO 4180 — [ Thread-4] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed
根据日志的线程名称很清楚的看出,每个异步方法在线程池的不同线程中执行。

FAQ
实际运行中,还出现过一个问题,一个Service中的方法调用自己的另一个方法,然后我将这个方法加上@Async注解,然而并不起作用。 异步方法都应该放到单独的异步任务Bean里面去,然后将这个Bean注入到Service中即可。

@Service
public class DeviceService {

    @Resource
    private AsyncTask asyncTask;
    
    public int unbind(Integer id, ManagerInfo managerInfo) {
        // 前面省略...
        
        // 开始异步推送消息
        asyncTask.pushUnbindMsg(managerInfo, pos, location);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 在Spring Boot中,我们可以通过自定义异步线程池来优化应用程序的性能。下面是一个简单的示例,演示如何在Spring Boot应用程序中自定义异步线程池: 1. 首先,我们需要在Spring Boot应用程序的配置文件中定义异步线程池的属性: ``` spring.task.execution.pool.core-size=10 spring.task.execution.pool.max-size=20 spring.task.execution.pool.queue-capacity=1000 ``` 上述配置定义了异步线程池的核心大小、最大大小和队列容量。 2. 然后,我们需要创建一个自定义的异步线程池配置类,如下所示: ``` @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(1000); executor.setThreadNamePrefix("MyCustomExecutor-"); executor.initialize(); return executor; } } ``` 上述配置类实现了AsyncConfigurer接口,并覆盖了getAsyncExecutor()方法,该方法返回一个自定义的ThreadPoolTaskExecutor对象,其中设置了异步线程池的核心大小、最大大小、队列容量和线程名称前缀。 3. 最后,在需要异步执行的方法上添加@Async注解即可: ``` @Service public class MyService { @Async public void doSomethingAsync() { // 异步执行的代码 } } ``` 上述示例中,我们在MyService类的doSomethingAsync()方法上添加了@Async注解,表示该方法需要异步执行。 这样,我们就成功地自定义了Spring Boot应用程序中的异步线程池。 ### 回答2: 在Spring Boot中,可以通过配置来自定义异步线程池。我们可以利用`@EnableAsync`注解开启异步支持,并使用`@Async`注解来标识需要异步执行的方法。 首先,在Spring Boot的配置文件(如application.properties或application.yml)中配置线程池的相关属性,例如线程池核心线程数、最大线程数、队列容量等。示例配置如下: ``` spring.task.execution.pool.core-size=10 spring.task.execution.pool.max-size=20 spring.task.execution.pool.queue-capacity=100 ``` 接下来,在启动类上添加`@EnableAsync`注解,以开启异步支持。例如: ```java @SpringBootApplication @EnableAsync public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 然后,我们可以在需要异步执行的方法上添加`@Async`注解,以告知Spring该方法需要异步执行。例如: ```java @Service public class MyService { @Async public void asyncMethod() { // 异步执行的方法体 } } ``` 在上述示例中,`asyncMethod()`方法会被Spring框架异步执行,Spring会自动从线程池中获取一个线程来执行该方法。 通过以上步骤,我们就可以在Spring Boot中自定义异步线程池。我们可以根据具体的业务需求来调整线程池的配置,以达到最佳的性能和资源利用效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alan丶K

各位技术大佬,小弟敲字不易

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值