@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();
	}
}
相关推荐
你的人类朋友12 小时前
说说签名与验签
后端
databook12 小时前
Manim实现脉冲闪烁特效
后端·python·动效
RainbowSea13 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea13 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
canonical_entropy16 小时前
AI时代,我们还需要低代码吗?—— 一场关于模型、演化与软件未来的深度问答
后端·低代码·aigc
颜如玉16 小时前
HikariCP:Dead code elimination优化
后端·性能优化·源码
考虑考虑17 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613517 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
bobz96518 小时前
virtio vs vfio
后端
浮游本尊18 小时前
Java学习第22天 - 云原生与容器化
java