Spring

生命周期

并发编程支持

Task Executor

Spring’s TaskExecutor is an abstraction around thread execution that decouples task submission from the mechanics of how each task will be run, including thread use, scheduling, and so on. It is very similar to Java’s ExecutorService.

  • Use @EnableAsync annotation on configuration class to enable async handling in Spring and the scanning of the @Async on methods.
  • Declare a ThreadPoolTaskExecutor bean in case more control on the thread pool is needed, otherwise a single thread pool is used by Spring.
  • Use @Async on methods to make them be executed in thread pool.
  • For the aysnc methods, Future and CompletableFuture return types are supported.
  • For Spring MVC, Spring supports returning a Callable, DeferredResult, or CompletableFuture from controller methods.

Task Scheduler

Spring's TaskScheduler is used for scheduling tasks to run either periodically or at a specific time. The most common implementation of TaskScheduler in Spring is ConcurrentTaskScheduler, which typically uses a ScheduledExecutorService for task scheduling.

  • Use @EnableScheduling annotation on configuration class to enable detection of @Scheduled annotations on any Spring-managed bean in the container.
  • Declare a ThreadPoolTaskScheduler bean in case more control on the thread pool is needed.
  • Define a bean that uses the TaskScheduler to run a scheduled task by annotating @Scheduled on the method.

Spring WebFlux

Spring WebFlux是Spring5.0引入的Reactive Web框架,它基于Netty和Project Reactor构建,提供了一个响应式的编程模型,可以用于使用少量的线程来处理大量的并发请求,用于构建响应式的RESTful服务。

从性能的角度来看,如果应用程序是I/O密集型的,与Spring MVC相比,使用Spring WebFlux可以缩短响应时间、减少线程和减少内存使用。

但是,由于其他关键组件如JDBC依然是基于BIO实现(虽然有项目R2DBC来提供Reactive的JDBC实现,但其成熟度有限),当要和这些组件协同工作时,使用WebFlux还需要同时使用另一个线程池来执行Blocking的任务,相对繁琐。

Spring Data

Spring Data的核心原理是基于Repository模式,开发者通过Repository接口来访问数据库,Spring Data会根据Repository接口的实现类自动生成实现类。

  • 开发者通过扩展CrudRepositoryPagingAndSortingRepository等接口来定义这个的Repository。
  • 通过解析方法名自动创建查询,方法名遵循以下规则。
    • 关键字分析:方法名以关键字开始,如find...By, read...By, query...By, count...By, 和 get...By。这些关键字让Spring Data知道方法将用于查询。
    • 条件查询:方法名中的条件表达式部分紧跟在By关键字之后,用于指定查询条件。例如,findByName表示查询中会有一个条件是根据name字段。
    • 连接条件:可以通过AndOr连接多个条件,如findByNameOrAge表示查询的条件是根据name或age字段。
    • 比较关键字:支持使用比较关键字如GreaterThan, LessThan, Between, Like等来进一步定义条件,如findByAgeGreaterThan表示查询age字段大于方法参数值的记录。
    • 排序:通过OrderBy后面跟属性名和AscDesc来指定排序方式,如findByAgeOrderByLastNameDesc表示根据age查询并按lastName降序排序。
  • 支持通过@Query注解来定义查询。QL语言可以使用JPQL(Java Persistence Query Language)或本地SQL语言。
    • JPQL例子:@Query("select u from User u where u.name =?1")
    • 本地SQL例子:@Query(value = "SELECT * FROM users WHERE email = ?1", nativeQuery = true)

Spring Kafka

参阅 Kafka