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

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

2019年04月08日 09:44:15 Shane_FZ_C 阅读数:37

 

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

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

 

内容概要

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

文件结构

在这里插入图片描述

环境jar包

 jdk: jdk1.8.0_121(32位)
		pom:
			 
	            org.springframework
	            spring-context
	            5.0.10.RELEASE
	        

配置类 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();
    }
}

输出结果

在这里插入图片描述

你可能感兴趣的:(项目实践,异步调用,controller,多线程解决方案)