啓動類:添加@EnableAsync註解java
@SpringBootApplication @EnableAsync public class Application{ public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
service方法上添加@Async註解spring
import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class UserService { @Async public void sendSms(){ System.out.println("####sendSms#### 2"); IntStream.range(0, 5).forEach(d -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println("####sendSms#### 3"); } }
配置框架
package com.boot.common.conf; import java.util.concurrent.ThreadPoolExecutor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * 線程池配置 * @author zhh * */ @Configuration @EnableAsync public class ThreadPoolTaskConfig { private static final int corePoolSize = 10; // 核心線程數(默認線程數) private static final int maxPoolSize = 100; // 最大線程數 private static final int keepAliveTime = 10; // 容許線程空閒時間(單位:默認爲秒) private static final int queueCapacity = 200; // 緩衝隊列數 private static final String threadNamePrefix = "Async-Service-"; // 線程池名前綴 @Bean("taskExecutor") // bean的名稱,默認爲首字母小寫的方法名 public ThreadPoolTaskExecutor taskExecutor(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setKeepAliveSeconds(keepAliveTime); executor.setThreadNamePrefix(threadNamePrefix); // 線程池對拒絕任務的處理策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 初始化 executor.initialize(); return executor; } }
測試異步
package com.boot.test1.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class TranTest2Service { Logger log = LoggerFactory.getLogger(TranTest2Service.class); // 發送提醒短信 1 @Async("taskExecutor") public void sendMessage1() throws InterruptedException { log.info("發送短信方法---- 1 執行開始"); Thread.sleep(5000); // 模擬耗時 log.info("發送短信方法---- 1 執行結束"); } // 發送提醒短信 2 @Async("taskExecutor") public void sendMessage2() throws InterruptedException { log.info("發送短信方法---- 2 執行開始"); Thread.sleep(2000); // 模擬耗時 log.info("發送短信方法---- 2 執行結束"); } }
以下方式會使@Async失效
1、異步方法使用static修飾
2、異步類沒有使用@Component註解(或其餘註解)致使spring沒法掃描到異步類
3、異步方法不能與異步方法在同一個類中
4、類中須要使用@Autowired或@Resource等註解自動注入,不能本身手動new對象
5、若是使用SpringBoot框架必須在啓動類中增長@EnableAsync註解
6、在Async 方法上標註@Transactional是沒用的。 在Async 方法調用的方法上標註@Transactional 有效。測試