springboot 异步任务

一、
1: 启动类里面使用@EnableAsync注解开启功能,自动扫描
2:在要异步任务的类上写@component
3:在定义异步任务类写@Async(写在类上代表整个类都是异步,在方法加上代表该类异步执行)
主类

@SpringBootApplication
@EnableAsync   //开启异步任务
@MapperScan("com.qdd.api.mapper.generate")
public class DemoApplication extends SpringBootServletInitializer {
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		// 注意这里要指向原先用main方法执行的Application启动类
		return builder.sources(DemoApplication.class);
	}

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

异步类

package com.qdd.api.util;

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

import java.util.concurrent.Future;

/**
 * 功能描述:异步任务业务类
 */
@Component
@Async
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");
    }
        
}

controller类

@Autowired
	private AsyncTask task;
	
	/**
	 *
	 * 功能描述: 异步任务测试
	 *
	 */
	@GetMapping("async_task")
	public String 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 "hello";
	}

返回结果

任务6耗时=1000
任务4耗时=2000
任务5耗时=3000
执行总耗时=3020

总结
从上面示例可以看出:如果同步方法,那需要6秒,而异步执行,只需要3秒左右,这就是异步的作用。
1)要把异步任务封装到类里面,不能直接写到Controller
2)增加Future 返回结果 AsyncResult(“task执行完成”);
3)如果需要拿到结果 需要判断全部的 task.isDone()

参考文章 https://www.cnblogs.com/qdhxhz/p/9058418.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值