@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();
	}
}
相关推荐
ladymorgana28 分钟前
【spring boot】三种日志系统对比:ELK、Loki+Grafana、Docker API
spring boot·elk·grafana
一只叫煤球的猫1 小时前
【🤣离谱整活】我写了一篇程序员掉进 Java 异世界的短篇小说
java·后端·程序员
斐波娜娜1 小时前
Maven详解
java·开发语言·maven
Bug退退退1231 小时前
RabbitMQ 高级特性之事务
java·分布式·spring·rabbitmq
程序员秘密基地1 小时前
基于html,css,vue,vscode,idea,,java,springboot,mysql数据库,在线旅游,景点管理系统
java·spring boot·mysql·spring·web3
皮皮林5512 小时前
自从用了CheckStyle插件,代码写的越来越规范了....
java
小码氓2 小时前
Java填充Word模板
java·开发语言·spring·word
会飞的天明2 小时前
Java 导出word 实现饼状图导出--可编辑数据
java·word
Muxiyale2 小时前
使用spring发送邮件,部署ECS服务器
java·服务器·spring
你的人类朋友2 小时前
🫏光速入门cURL
前端·后端·程序员