SpringBoot 第二十一篇 异步线程池

本文详细介绍了如何在Spring框架中配置和使用异步任务,包括实现AsyncConfigurer接口来自定义线程池,以及使用@EnableAsync和@Async注解启用和标记异步方法。通过示例展示了完整的异步任务配置流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 简介

   在spring中 存在着一个AsyncConfigurer 接口,它是一个可以配置异步线程池的接口,

   源码如下:

    

public interface AsyncConfigurer {

    // 获取线程池   
    @org.springframework.lang.Nullable
    default java.util.concurrent.Executor getAsyncExecutor() { /* compiled code */ }

    // 异步异常处理器
    @org.springframework.lang.Nullable
    default org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { /* compiled code */ }
}

 getAsyncExecutor 返回的自定义线程池,这样在开启异步时,线程池会提供空闲

 线程来执行异步任务。

getAsyncUncaughtExceptionHandler: 异常处理器。

因此只需要java配置文件,实现AsyncConfigurer 接口,实现getAsysncExecutor

方法返回的线程池,这样spring就会使用这个线程池作为异步调用的线程。

为了使异步可用,spring还提供@EnableAsync,如果java配置文件标注它,那么spring

会开启异步可用,这样就可使用@Async 驱动spring 使用异步调用。

示例:

   1. 使用Java配置定义线程池,和启动异步。

package com.chenyun.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 在代码中,注解@EnableAsyanc代表开启spring异步,这样可以使用@async驱动spring使用异步
 * 但异步需要提供可用线程池,所以这里配置类会实现AsyncConfigurer接口,然后覆盖
 * getAsyncExecutor方法,这样就可以自定义一个线程池。因此当方法标注@Async时,
 * spring就会通过这个线程池的空闲线程去运行该方法。
 * */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    //定义线程池
    @Override
    public Executor getAsyncExecutor(){

        // 定义线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();

        // 核心线程数
        taskExecutor.setCorePoolSize(100);

        // 线程池最大线程数
        taskExecutor.setMaxPoolSize(300);

        //线程队列最大线程数
        taskExecutor.setQueueCapacity(2000);

        // 初始化
        taskExecutor.initialize();

        return taskExecutor;


    }
}

   2.  异步接口

package com.chenyun.service;

public interface AsyncService {

    public void generateReport();
}

3 . 异步方法实现

package com.chenyun.service.impl;

import com.chenyun.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl implements AsyncService {

    @Override
    @Async  // 声明使用异步调用
    public void generateReport(){

        //打印异步线程的名称
        System.out.println("报表县城名称:"+Thread.currentThread().getName());
    }
}

4. 异步控制器

package com.chenyun.web;

import com.chenyun.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @RequestMapping("/async")
    public void generateReport(){
        System.out.println("请求线程的名称:"+ Thread.currentThread().getName());
        asyncService.generateReport();
    }




}

 

 

 

 

### 回答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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值