需要運行一些調度任務,但是又不想放到web容器中運行。 見紅色代碼:
import java.util.concurrent.ThreadPoolExecutor; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @SpringBootApplication @EnableCaching @EnableRedisHttpSession @EnableAsync @EnableScheduling public class JspxScheduleApplication { public static void main(String[] args) { new SpringApplicationBuilder(JspxScheduleApplication.class).web(WebApplicationType.NONE).run(args); } @Bean public AsyncTaskExecutor asyncTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("jspt-schedule-"); executor.setMaxPoolSize(30); executor.setCorePoolSize(10); executor.setQueueCapacity(0); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); return executor; } }
WebApplicationType 有三個值。
NONE
- 應用程序不應作為Web應用程序運行,也不應啟動嵌入式Web服務器。REACTIVE
- 應用程序應作為響應式Web應用程序運行,並應啟動嵌入式響應式Web服務器。
SERVLET
- 應用程序應作為基於servlet的Web應用程序運行,並應啟動嵌入式servlet Web服務器。