@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 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
CJi0NG1 小时前
【自用】JavaSE--算法、正则表达式、异常
java
Nejosi_念旧1 小时前
解读 Go 中的 constraints包
后端·golang·go
风无雨1 小时前
GO 启动 简单服务
开发语言·后端·golang
Hellyc1 小时前
用户查询优惠券之缓存击穿
java·redis·缓存
小明的小名叫小明1 小时前
Go从入门到精通(19)-协程(goroutine)与通道(channel)
后端·golang
斯普信专业组1 小时前
Go语言包管理完全指南:从基础到最佳实践
开发语言·后端·golang
今天又在摸鱼2 小时前
Maven
java·maven
老马啸西风2 小时前
maven 发布到中央仓库常用脚本-02
java·maven
代码的余温2 小时前
MyBatis集成Logback日志全攻略
java·tomcat·mybatis·logback