【SpringBoot基础】@Async 异步处理注解实现

【SpringBoot基础】@Async 异步处理注解实现

    • 内容概要
    • 文件结构
    • 环境jar包
    • 配置类 TaskExecutorConfig
    • 异步方法类 AsyncTaskService
    • 测试类Main
    • 输出结果

内容概要

注解实现异步多线程非阻塞。

文件结构

【SpringBoot基础】@Async 异步处理注解实现_第1张图片

环境jar包

 jdk: jdk1.8.0_121(32位)
		pom:
			 <dependency>
	            <groupId>org.springframework</groupId>
	            <artifactId>spring-context</artifactId>
	            <version>5.0.10.RELEASE</version>
	        </dependency>

配置类 TaskExecutorConfig

 package com.Async;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
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.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.Executor;
@Configuration
@EnableAsync //启用异步
@ComponentScan("com.Async")
public class TaskExecutorConfig implements AsyncConfigurer {//实现异步接口
	//异步线程池配置
    public Executor getAsyncExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5);//常规线程数量
        threadPoolTaskExecutor.setMaxPoolSize(10);//最大线程数量
        threadPoolTaskExecutor.setQueueCapacity(100);//等待执行线程队列数量
        threadPoolTaskExecutor.initialize();//构建
        return threadPoolTaskExecutor;
    }
	
}

异步方法类 AsyncTaskService

package com.Async;

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

@Service
public class AsyncTaskService {
    @Async //注解异步方法
    public void execute(Integer i) {
        System.out.println("执行异步输出execute: "+i);
    }
    @Async
    public void executeAsyncTaskPlus(Integer i){
        System.out.println("执行异步输出executeAsyncTaskPlus: "+i);
    }
}

测试类Main

package com.Async;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String  [] args){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
        AsyncTaskService bean = applicationContext.getBean(AsyncTaskService.class);
        for (int i = 0;i < 10; i++){
            bean.execute(i);
            bean.executeAsyncTaskPlus(i);
        }
        applicationContext.close();
    }
}

输出结果

【SpringBoot基础】@Async 异步处理注解实现_第2张图片

你可能感兴趣的:(SpringBoot)