一、任务执行和调度

1、TaskExecutor

Spring 的**TaskExecutor**接口与java.util.concurrent.Executor接口相同。实际上,最初,它存在的主要原因是在使用线程池时抽象出对 Java 5 的需求。该接口具有单个方法(execute(Runnable task)),该方法基于线程池的语义和 configuration 接受要执行的任务。
实现类

  • **SyncTaskExecutor**:此 实现类 不会异步执行调用。相反,每次调用都发生在调用线程中。它主要用于不需要 多线程的情况,这个类没有实现异步调用,只是一个同步操作。只适用于不需要多线程的地方。
  • SimpleAsyncTaskExecutor:此 实现类不会重用任何线程。相反,它为每次调用启动一个新线程。但是,它确实支持并发限制,该限制会阻止任何超出限制的调用,直到释放一个插槽,每次都会创建一个新的线程。
  • **ConcurrentTaskExecutor**:此 实现类是java.util.concurrent.Executor实例的适配器,Executor的适配类,不推荐使用。如果ThreadPoolTaskExecutor不满足要求时,才用考虑使用这个类。
  • ThreadPoolTaskExecutor:此 实现类 最常用。它公开 bean properties 以配置java.util.concurrent.ThreadPoolExecutor并将其包装在TaskExecutor中。如果您需要适应不同类型的java.util.concurrent.Executor,我们建议您改用ConcurrentTaskExecutor。默认一个核心,最大线程Integer.Max,等待时间60s. 配置Bean的时候需要配置好信息。

    1. <bean id="taskExecutor"
    2. class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    3. <!-- 核心线程数,线程池里最小线程数 -->
    4. <property name="corePoolSize" value="10" />
    5. <!-- 最大线程数 -->
    6. <property name="maxPoolSize" value="100" />
    7. <!-- 队列最大长度 -->
    8. <property name="queueCapacity" value="1000" />
    9. <!-- 线程池维护线程所允许的空闲时间 -->
    10. <property name="keepAliveSeconds" value="300" />
    11. <!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
    12. <property name="rejectedExecutionHandler">
    13. <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
    14. </property>
    15. </bean>
  • WorkManagerTaskExecutor:此 implementation 使用 CommonJ WorkManager作为其后备服务提供程序,并且是在 Spring application context 中在 WebLogic 或 WebSphere 上设置 CommonJ-based 线程池 integration 的中心便捷 class。

  • DefaultManagedTaskExecutor:此 implementation 在 JSR-236 兼容的运行时环境(例如 Java EE 7 application 服务器)中使用 JNDI-obtained ManagedExecutorService,为此目的替换 CommonJ WorkManager。

    2、定时任务

    2.1 Spring TaskScheduler 抽象,接口如下:

    ```java public interface TaskScheduler {

    ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Instant startTime);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Instant startTime, Duration period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Duration period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Duration delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay); }

//实现 scheduler.schedule(task, new CronTrigger(“0 15 9-17 MON-FRI”));

  1. ** 注解开发**<br />**@EnableScheduling 启动定时器**<br />要启用对`@Scheduled`和`@Async` 注释的支持,可以将`@EnableScheduling`和`@EnableAsync`添加到其中一个`@Configuration` classes 中,如果您只需要支持`@Scheduled`,则可以省略`@EnableAsync`或者xml如下
  2. ```xml
  3. <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
  4. <task:executor id="myExecutor" pool-size="5"/>
  5. <task:scheduler id="myScheduler" pool-size="10"/>

实例如下:

//固定每5秒调用一次 ,初始延时多久调用
@Scheduled(fixedDelay=5000,initialDelay=1000)
public void doSomething() {
    // something that should execute periodically
}

或者直接使用cron 表达式:

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
    // something that should execute on weekdays only
}

请确保不要在使用@``**Scheduled**注释的 bean classes 上使用@``**Configurable**,并将其作为常规 Spring beans 注册到容器中。否则,您将获得 double 初始化(一次通过容器,一次通过@Configurable aspect),每次@Scheduled方法的结果被调用两次。

您可以在方法上提供@Async annotation,以便异步调用该方法。换句话说,调用者在调用时立即返回,而方法的实际执行发生在已提交给 Spring TaskExecutor的任务中。
在最简单的情况下,您可以将 annotation 应用于返回void的方法。

@Async
void doSomething(String s) {
    // this will be executed asynchronously
}
//有返回值
@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
}
//指定特定的异步执行器
@Async("otherExecutor")
...

定时任务组件的区别:

组件名称 cron 持久化 开发难以程度
schedule 支持 不支持 非常简单
quartz 支持 支持 复杂

简单的可以直接使用schedule,复杂的使用quartz进行任务调度,quartz还支持持久化,动态设置定时任务等。

2.2 quartz

官网:http://quartz-scheduler.org。
…后续补充…

三、Spring 缓存

Spring 提供了一些实现的抽象:基于 JDK java.util.concurrent.``**ConcurrentMap**的缓存

要启用缓存注释,请将注释**@EnableCaching**添加到**@Configuratio**

  • @Cacheable:查找数据 ```java //允许指定多个名称,以便使用多个缓存。 //在这种情况下,在执行方法之前检查每个缓存 - 如果至少有一个缓存被命中,则返回关联的 value。 @Cacheable(“books”) //等效于cacheNames=”books” public Book findBook(ISBN isbn) {…}

//缓存同步 @Cacheable(cacheNames=”foos”, sync=true) public Book findBook(ISBN isbn) {…}

//条件缓存,只有满足条件才进行缓存 @Cacheable(cacheNames=”book”, condition=”#name.length() < 32”) public Book findBook(String name) //可以使用SPEL 表达是使用


   - `@CacheEvict`:触发缓存逐出。
```java
//使用allEntries属性删除缓存中的所有数据。
@CacheEvict(cacheNames="books", allEntries=true) 
public void loadBooks(InputStream batch)
  • @CachePut:更新缓存而不会干扰方法执行,不要再同一个地方使用@CachePut和Cacheable,写入缓存。

    @CachePut(cacheNames="book", key="#isbn")
    public Book updateBook(ISBN isbn, BookDescriptor descriptor)
    
  • @Caching:重新组合要在方法上应用的多个缓存操作。

    // 嵌套多个缓存操作
    @Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
    public Book importBooks(String deposit, Date date)
    
  • @CacheConfig:在 class-level 分享一些 common cache-related 设置。

使用@CacheConfig设置缓存的名字

@CacheConfig("books") (1)
public class BookRepositoryImpl implements BookRepository {

    @Cacheable
    public Book findBook(ISBN isbn) {...}
}
  • 首先执行@CacheEvict(如果beforeInvocation=true且condition 通过),如果allEntries=true,则清空所有
  • 接着收集@Cacheable(如果condition 通过,且key对应的数据不在缓存),放入cachePutRequests(也就是说如果cachePutRequests为空,则数据在缓存中)
  • 如果cachePutRequests为空且没有@CachePut操作,那么将查找@Cacheable的缓存,否则result=缓存数据(也就是说只要当没有cache put请求时才会查找缓存)
  • 如果没有找到缓存,那么调用实际的API,把结果放入result
  • 如果有@CachePut操作(如果condition 通过),那么放入cachePutRequests
  • 执行cachePutRequests,将数据写入缓存(unless为空或者unless解析结果为false);
  • 执行@CacheEvict(如果beforeInvocation=false 且 condition 通过),如果allEntries=true,则清空所有