From 53cce93ee01a1da00412f8d98378c562b6a47b10 Mon Sep 17 00:00:00 2001 From: wu xiangkai Date: Fri, 6 Jan 2023 13:00:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A5=E5=B8=B8=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring/spring boot/Spring Boot Async.md | 84 ++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/spring/spring boot/Spring Boot Async.md b/spring/spring boot/Spring Boot Async.md index ef02e37..b06d517 100644 --- a/spring/spring boot/Spring Boot Async.md +++ b/spring/spring boot/Spring Boot Async.md @@ -97,4 +97,86 @@ scheduler.schedule(task, new CronTrigger("0 15 9-17 * * MON-FRI")); ``` Spring的另一个Trigger实现是PeriodicTrigger,其接受一个固定的period期间,一个可选的初始delay值,并接收一个boolean值标识该period是fixed-rate还是fixed-delay。 ### TaskScheduler实现类 -如果不需要外部的线程管理,可以使用spring提供的ThreadPoolTaskScheduler,其会将任务委托给ScheduledExecutorService来提供bean-properties形式的配置。 \ No newline at end of file +如果不需要外部的线程管理,可以使用spring提供的ThreadPoolTaskScheduler,其会将任务委托给ScheduledExecutorService来提供bean-properties形式的配置。 + +## 对任务调度和异步执行的注解支持 +Spring同时对任务调度和异步方法的执行提供注解支持。 +### 启用Scheduling注解 +想要启用@Async和@Scheduled注解,必须将@EnableAsync注解和@EnableScheduling注解添加到一个@Configuration类上。 +```java +@Configuration +@EnableAsync +@EnableScheduling +public class AppConfig { +} +``` +> **@Async注解的实现是通过proxy模式来实现的,故而如果在类内部调用位于同一个类中的@Async方法,那么代理拦截会失效,此时调用的@Async方法将会同步执行而非异步执行** + +> @Async可以接收一个value值,用于指定目标的执行器(Executor或TaskExecutor的beanName) + +### @Scheduled注解 +在将@Scheduled注解标注到方法时,可以为其指定一个trigger的元数据,使用示例如下: +```java +@Scheduled(fixedDelay = 5000) +public void doSomething() { + // something that should run periodically +} +``` +> 默认情况下,fixedDelay、fixedRate、initialDelay的时间单位都是ms,可以指定timeUnit来指定其他的时间单位: +> ```java +> @Scheduled(fixedDelay = 5, timeUnit = TimeUnit.SECONDS) +> public void doSomething() { +> // something that should run periodically +> } +> ``` + +可以为@Scheduled注解使用cron表达式 +```java +@Scheduled(cron="*/5 * * * * MON-FRI") +public void doSomething() { + // something that should run on weekdays only +} +``` + +### @Async注解 +通过为方法指定@Async注解,可以让该方法异步执行,该方法的执行通过TaskExecutor。 +```java +@Async +void doSomething() { + // this will be run asynchronously +} +``` +可以为@Async标注的方法指定参数和返回值,但是异步方法的返回值只能为void或是Future类型。 +在该异步方法的调用方调用返回Future实例的get方法之前,调用方仍然能够执行其他操作,异步方法的执行位于TaskExecutor的线程中。 +```java +@Async +Future returnSomething(int i) { + // this will be run asynchronously +} +``` +不能将@Async注解和生命周期回调(例如@PostConstruct)进行混用,如果想要异步的初始化bean对象,需要按照如下方法: +```java +public class SampleBeanImpl implements SampleBean { + + @Async + void doSomething() { + // ... + } + +} + +public class SampleBeanInitializer { + + private final SampleBean bean; + + public SampleBeanInitializer(SampleBean bean) { + this.bean = bean; + } + + @PostConstruct + public void initialize() { + bean.doSomething(); + } + +} +``` \ No newline at end of file