springboot 异步任务完美执行

异步调用

启动类:添加@EnableAsync注解

@SpringBootApplication
@EnableAsync
public class Application{
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

异步任务执行类 添加@Async注解

import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

/**
 * 功能描述:异步任务业务类(@Async也可添加在方法上)
 */
@Component
@Async("taskExecutor")
public class AsyncTask {
    

    //获取异步结果
    public Future<String> task4() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(2000L);
        long end = System.currentTimeMillis();
        System.out.println("任务4耗时="+(end-begin));
        return new AsyncResult<String>("任务4");
    }
    
    
    public Future<String> task5() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(3000L);
        long end = System.currentTimeMillis();
        System.out.println("任务5耗时="+(end-begin));
        return new AsyncResult<String>("任务5");
    }
    
    public Future<String> task6() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任务6耗时="+(end-begin));
        return new AsyncResult<String>("任务6");
    }
        
}

异步线程池

配置

package com.boot.common.conf;
 
import java.util.concurrent.ThreadPoolExecutor;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
/**
 * 线程池配置
 * @author zhh
 *
 */
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
	
	private static final int corePoolSize = 10;       		// 核心线程数(默认线程数)线程池创建时候初始化的线程数
	private static final int maxPoolSize = 100;			    // 最大线程数 线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
	private static final int keepAliveTime = 10;			// 允许线程空闲时间(单位:默认为秒)当超过了核心线程之外的线程在空闲时间到达之后会被销毁
	private static final int queueCapacity = 200;			// 缓冲队列数 用来缓冲执行任务的队列
	private static final String threadNamePrefix = "Async-Service-"; // 线程池名前缀 方便我们定位处理任务所在的线程池
	
	@Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
	public ThreadPoolTaskExecutor taskExecutor(){
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(corePoolSize);   
		executor.setMaxPoolSize(maxPoolSize);
		executor.setQueueCapacity(queueCapacity);
		executor.setKeepAliveSeconds(keepAliveTime);
		executor.setThreadNamePrefix(threadNamePrefix);
		
		// 线程池对拒绝任务的处理策略 采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		// 初始化
		executor.initialize();
		return executor;
	}
}

 

异步任务执行 controller

import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jincou.task.AsyncTask;
import com.jincou.util.JsonData;

@RestController
@RequestMapping("/api/v1")
public class UserController {
    
    @Autowired
    private AsyncTask task;
    
    @GetMapping("async_task")
    public JsonData exeTask() throws InterruptedException{
        
        long begin = System.currentTimeMillis();
        
        Future<String> task4 = task.task4();
        Future<String> task5 = task.task5();
        Future<String> task6 = task.task6();
        
        //如果都执行往就可以跳出循环,isDone方法如果此任务完成,true
        for(;;){
            if (task4.isDone() && task5.isDone() && task6.isDone()) {
                break;
            }
        }
                
        long end = System.currentTimeMillis();    
        long total = end-begin;
        System.out.println("执行总耗时="+total);
        return JsonData.buildSuccess(total);
    }    
}

使用异步任务比同步任务耗时少

注意事项:

如下方式会使@Async失效
一、异步方法使用static修饰
二、异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
三、异步方法不能与调用异步方法的方法在同一个类中
四、类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
五、如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解
六、在Async 方法上标注@Transactional是没用的。 在Async 方法调用的方法上标注@Transactional 有效。

  • 2
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,异步任务可以使用 `@Async` 注解来实现。使用 `@Async` 注解的方法会在一个单独的线程执行,从而避免了长时间的阻塞。 以下是实现异步任务的步骤: 1. 在 Spring Boot 应用的主类上添加 `@EnableAsync` 注解,启用异步任务。 ```java @EnableAsync @SpringBootApplication public class Application { // ... } ``` 2. 在需要异步执行的方法上添加 `@Async` 注解。该方法的返回值类型必须是 `java.util.concurrent.Future`,以便在需要时获取异步任务执行结果。 ```java @Service public class MyService { @Async public Future<String> doSomething() throws InterruptedException { // 模拟一个耗时的操作 Thread.sleep(5000); return new AsyncResult<>("Done"); } } ``` 3. 在需要调用异步方法的地方,使用 `Future` 对象获取异步任务执行结果。 ```java @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/async") public String asyncMethod() throws InterruptedException, ExecutionException { Future<String> future = myService.doSomething(); while (!future.isDone()) { // 等待异步任务完成 Thread.sleep(1000); } return future.get(); } } ``` 以上就是使用 `@Async` 注解实现异步任务的步骤。需要注意的是,异步任务执行需要在一个单独的线程中进行,因此需要在应用程序中配置线程池,以便管理异步任务线程。可以使用 Spring Boot 中的 `ThreadPoolTaskExecutor` 来实现线程池的配置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值