springboot 异步方法

本文详细介绍SpringBoot中异步方法的配置与使用,通过示例代码展示如何在不阻塞主线程的情况下执行耗时操作,提高应用响应速度。

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


springboot 异步方法

 

作用:在一个方法内调用异步方法,原方法不阻塞继续运行,异步方法可异步执行

 

 

****************************

示例

 

******************

config 层

 

TaskExecutorConfig:配置异步线程池

@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(10);
        executor.setKeepAliveSeconds(10);
        executor.initialize();

        return executor;
    }
}

 

******************

service 层

 

TaskService

@Service
public class TaskService {

    public void task(){
        System.out.println("task 开始运行:"+System.currentTimeMillis());

        try{
            Thread.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("task 运行结束:"+System.currentTimeMillis());
    }

    @Async
    public void task2(){
        System.out.println("task2 开始运行:"+System.currentTimeMillis());

        try{
            Thread.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("task2 运行结束:"+System.currentTimeMillis());
    }
}

 

******************

controller 层

 

HelloController

@RestController
public class HelloController {

    @Resource
    private TaskService taskService;

    @RequestMapping("/hello")
    public String hello(){
        System.out.println("开始调用task任务:"+System.currentTimeMillis());
        taskService.task();
        System.out.println("task任务调用结束:"+System.currentTimeMillis());

        return "success";
    }

    @RequestMapping("/hello2")
    public String hello2(){
        System.out.println("开始调用task2任务:"+System.currentTimeMillis());
        taskService.task2();
        System.out.println("task2任务调用结束:"+System.currentTimeMillis());

        return "success 2";
    }
}

 

 

****************************

控制台输出

 

/hello

开始调用task任务:1577101307042
task 开始运行:1577101307042
task 运行结束:1577101308042
task任务调用结束:1577101308042

 

/hello2

开始调用task2任务:1577101309740
task2任务调用结束:1577101309741
task2 开始运行:1577101309741
task2 运行结束:1577101310754

任务task2以异步方式被调用

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值