@Async 异步注解使用

@Async 异步注解使用

使用版本SpringBoot-2.7.18

使用@EnableAsync开启异步注解
java 复制代码
@EnableAsync
@SpringBootApplication
public class TestApplication {

	public static void main(String[] args) {
		SpringApplication.run(TestApplication.class, args);
	}

}
在需要的方法上加上@Async
java 复制代码
@Service
public class TestServiceImpl implements TestService {

	@Override
	@Async
	public LocalDateTime async() {
		return LocalDateTime.now();
	}
}
Spring Boot使用的异步任务执行器
默认情况异步任务执行器使用ThreadPoolTaskExecutor

org.springframework.aop.interceptor.AsyncExecutionInterceptor.invoke() 方法中打断点可以看到使用的是哪个线程池

java 复制代码
@Override
@Nullable
public Object invoke(final MethodInvocation invocation) throws Throwable {
    Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
    Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
    final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
    //1、这里打个断点可以看到使用的是哪个线程池
    AsyncTaskExecutor executor = determineAsyncExecutor(userDeclaredMethod);
    if (executor == null) {
        throw new IllegalStateException(
            "No executor specified and no default executor set on AsyncExecutionInterceptor either");
    }

    Callable<Object> task = () -> {
        try {
            Object result = invocation.proceed();
            if (result instanceof Future) {
                return ((Future<?>) result).get();
            }
        }
        catch (ExecutionException ex) {
            handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
        }
        catch (Throwable ex) {
            handleError(ex, userDeclaredMethod, invocation.getArguments());
        }
        return null;
    };

    return doSubmit(task, executor, invocation.getMethod().getReturnType());
}
直接配置一个异步任务执行器,使用@Async注解,异步任务执行器会更改成 myTaskExecutorA
java 复制代码
@Configuration
public class BeanConfigure {
	@Bean
	TaskExecutor myTaskExecutorA() {
		return new MyTaskExecutorA();
	}
	public static class MyTaskExecutorA implements TaskExecutor {
		@Override
		public void execute(Runnable task) {
			System.err.println("==========》" + task.getClass());
		}
	}
}
恰巧我们配置了两个异步任务执行器,会切换使用 org.springframework.core.task.SimpleAsyncTaskExecutor
java 复制代码
@Configuration
public class BeanConfigure {
	@Bean
	TaskExecutor myTaskExecutorA() {
		return new MyTaskExecutorA();
	}

	@Bean
	TaskExecutor myTaskExecutorB() {
		return new MyTaskExecutorB();
	}

	public static class MyTaskExecutorA implements TaskExecutor {
		@Override
		public void execute(Runnable task) {
			System.err.println("==========》" + task.getClass());
		}
	}

	public static class MyTaskExecutorB implements TaskExecutor {
		@Override
		public void execute(Runnable task) {
			System.err.println("==========》" + task.getClass());
		}
	}
}

首先, org.springframework.core.task.SimpleAsyncTaskExecutor执行效果不是很好;其次,项目中的其他业务可能会配置使用多于两个的TaskExecutor,所以使用@Async的最佳实践是为其明确指定异步任务执行器:@Async("myTaskExecutorA")

java 复制代码
@Service
public class TestServiceImpl implements TestService {

	@Override
	@Async("myTaskExecutorA")//明确指定需要使用的异步执行器
	public LocalDateTime async() {
		return LocalDateTime.now();
	}
}
相关推荐
代码小将1 小时前
Leetcode209做题笔记
java·笔记·算法
专注_每天进步一点点1 小时前
idea 启动Springboot项目在编译阶段报错:java: OutOfMemoryError: insufficient memory
java·spring boot·intellij-idea
dhxhsgrx2 小时前
PYTHON训练营DAY25
java·开发语言·python
不知几秋3 小时前
数字取证-内存取证(volatility)
java·linux·前端
chxii6 小时前
5java集合框架
java·开发语言
weixin_545019327 小时前
微信小程序智能商城系统(uniapp+Springboot后端+vue管理端)
spring boot·微信小程序·uni-app
IsPrisoner7 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
yychen_java7 小时前
R-tree详解
java·算法·r-tree
JANYI20187 小时前
嵌入式设计模式基础--C语言的继承封装与多态
java·c语言·设计模式