@EnableAsync和@Async开始异步任务支持

Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor.在开发中实现异步任务,我们可以在配置类中添加@EnableAsync开始对异步任务的支持,并在相应的方法中使用@Async注解来声明一个异步任务。
配置类

package com.xingguo.logistics.controller;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@ComponentScan({"com.xingguo.logistics.service.aspect","com.xingguo.logistics.service.event"})
//开始异步支持
@EnableAsync
public class AopConfig implements AsyncConfigurer{

    @Override
    public Executor getAsyncExecutor() {
         //线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
         return null;
    }

}

任务执行service类

package com.xingguo.logistics.service.aspect;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TestService2 {

    //声明异步任务
    @Async
    public void executeAsyncTask(Integer i){
         System.out.println("执行异步任务:"+i);
    }

    @Async
    public void executeAsyncTask2(Integer i){
         System.out.println("执行异步任务2:"+i);
    }

}

测试类

package com.xingguo.logistics.controller;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.xingguo.logistics.service.aspect.TestService2;

public class TestController {

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);

    TestService2 testService2 = context.getBean(TestService2.class);
    for(int i = 0; i<10; i++){
        testService2.executeAsyncTask(i);
        testService2.executeAsyncTask2(i);
    }
    context.close();

    }
}

测试结果如下:
这里写图片描述
执行结果可以看出,并没有按照顺序来执行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值