Spring @Async执行异步方法的简单使用
发布日期:2025-05-01 22:47:18 浏览次数:12 分类:精选文章

本文共 3449 字,大约阅读时间需要 11 分钟。

Spring @Async 异步方法的简单使用指南

开启Spring的异步处理支持

为了在Spring应用中实现异步方法执行,首先需要配置异步处理支持。可以通过在配置类中添加相应的注解来实现。

@Configuration
@EnableAsync
public class SpringAsyncConfig {
// 配置异步线程池等执行器(如下文所示)
}

@Async注解的使用

@Async注解用于标记需要异步执行的方法。它将切点方法从主线程中脱离,转为异步执行。

@Service
public class UserServiceImpl implements UserService {
@Async
public void printUser(String user) {
log.info(Thread.currentThread().getName() + "---------Looking up " + user);
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(Thread.currentThread().getName() + "---------user----------------> " + user);
return;
}
@Async
public String getUser0(String user) {
log.info(Thread.currentThread().getName() + "---------Looking up " + user);
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
String result = "hello " + user;
log.info(Thread.currentThread().getName() + "---------user----------------> " + user);
return result;
}
@Async
public CompletableFuture
getUser(String user) {
log.info(Thread.currentThread().getName() + "---------Looking up " + user);
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
String result = "hello " + user;
log.info(Thread.currentThread().getName() + "---------user----------------> " + user);
return CompletableFuture.completedFuture(result);
}
}

调用异步方法

在控制器或服务层调用异步方法后,需等待其完成。可以通过CompletableFuture获取结果,或者在方法返回类型中直接使用异步方法返回结果。

@RestController
public class TestController {
@Autowired
private UserService userService;
@GetMapping("/test")
public String test() {
userService.printUser("Jack");
return Thread.currentThread().getName() + "-----" + "void";
}
@GetMapping("/test2")
public String test2() {
String result = userService.getUser0("Jack");
return Thread.currentThread().getName() + "-----" + result;
}
@GetMapping("/test3")
public String test3() throws Exception {
CompletableFuture
result = userService.getUser("Jack");
String user = result.get();
return Thread.currentThread().getName() + "-----" + user;
}
}

配置自定义异步执行器

你也可以配置自定义的线程池来执行异步任务。在Spring配置类中添加相应的bean配置。

@Configuration
@EnableAsync
public class SpringAsyncConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
return executor;
}
}

@Async注解不生效的原因

如果@Async注解没有生效,可能是以下原因之一:

  • SpringBootApplication启动类未添加@EnableAsync注解:确保主类被正确注解,启用异步支持。

  • 异步方法返回值不是void或Future:@Async注解仅作用于返回void或Future类型的方法。

  • 方法不是public方法:确保方法是public的,否则无法被Spring代理。

  • 解决方法

  • 确保@Async注解的方法是public方法。

  • 从外部类调用方法,类内调用无效。

  • 如果需要内部调用,通过@Autowired获取服务bean后调用。

  • 总结

    通过上述配置和使用方法,你可以轻松实现Spring中的异步方法执行。配置@Async注解和自定义线程池后,就可以高效处理I/O密集型任务,提升应用性能。

    上一篇:PAT (Basic Level) Practice 乙级1021-1030
    下一篇:Spring Boot 动态加载jar包,动态配置太强了!

    发表评论

    最新留言

    关注你微信了!
    [***.104.42.241]2026年05月26日 04时11分06秒