Spring 之异步执行

很多业务场景只需要发送请求而不必等待结果的返回,此时就需要线程异步场景的调用。

方式一:

1.首先初始化bean:

@Configuration
public class TaskExecutorConfig {

    @Qualifier("taskExecutor2")
    @Bean
    public TaskExecutor executor(){
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        executor.initialize();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(5);
        return executor;
    }

}

2.service层写需要异步执行的业务操作,此处为了测试方便直接写controller

@Autowired
@Qualifier("taskExecutor2")
private TaskExecutor taskExecutor2;


。。。



taskExecutor2.execute((new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(5000);
                        System.out.println("task running ...");
                    } catch (Exception e) {

                    }
                }
            }
        }));
        Map res = new HashMap();
        System.out.println("===");
        res.put("result", "success");
        return res;

此时会立即返回res的map,五秒钟后自动执行后台任务

此处 @Qualifier("taskExecutor2")是为了防止自动装配的歧义性

方式二:

通过

org.springframework.scheduling.annotation.Async的 @Async
@Component
@EnableAsync
public class AsyncTest_1 {
    @Async
    public void hello_1() throws InterruptedException {
        System.out.println("hello_1开始执行");
        TimeUnit.MILLISECONDS.sleep(2000);
        System.out.println("hello_1执行完毕");
    }
}
@Component
@EnableAsync
public class AsyncTest_2 {
    @Async
    public void hello_2() throws InterruptedException {
        System.out.println("hello_2开始执行");
        TimeUnit.MILLISECONDS.sleep(3000);
        System.out.println("hello_2执行完毕");

    }
}
@Component
@EnableAsync
public class AsyncTest_3 {

    @Async
    public void hello_3() throws InterruptedException {
        System.out.println("hello_3开始执行");
        TimeUnit.MILLISECONDS.sleep(5000);
        System.out.println("hello_3执行完毕");


    }
}

 

测试类:

   Map map=new HashMap();
       long startTime= System.currentTimeMillis();
        asyncTest_3.hello_3();
        asyncTest_1.hello_1();
        asyncTest_2.hello_2();
        long time=(System.currentTimeMillis()-startTime)/1000;
        System.out.println(time);
        map.put("result",true);
        return map;

测试类会立即返回map结果,hello_1、hello_2、hello_3后台异步执行

首先@Async针对Spring的bean起作用,用在普通方法是无效的

必须用@EnableAsync注解使@Async生效才可以,默认是false

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值