本文共 3449 字,大约阅读时间需要 11 分钟。
为了在Spring应用中实现异步方法执行,首先需要配置异步处理支持。可以通过在配置类中添加相应的注解来实现。
@Configuration@EnableAsyncpublic class SpringAsyncConfig { // 配置异步线程池等执行器(如下文所示)} @Async注解用于标记需要异步执行的方法。它将切点方法从主线程中脱离,转为异步执行。
@Servicepublic 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获取结果,或者在方法返回类型中直接使用异步方法返回结果。
@RestControllerpublic 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@EnableAsyncpublic 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注解没有生效,可能是以下原因之一:
SpringBootApplication启动类未添加@EnableAsync注解:确保主类被正确注解,启用异步支持。
异步方法返回值不是void或Future:@Async注解仅作用于返回void或Future类型的方法。
方法不是public方法:确保方法是public的,否则无法被Spring代理。
确保@Async注解的方法是public方法。
从外部类调用方法,类内调用无效。
如果需要内部调用,通过@Autowired获取服务bean后调用。
通过上述配置和使用方法,你可以轻松实现Spring中的异步方法执行。配置@Async注解和自定义线程池后,就可以高效处理I/O密集型任务,提升应用性能。
转载地址:http://fxvfk.baihongyu.com/