@Async的用法和示例


@Async 注解的用法和示例

背景

通常,在Java中的方法調用都是同步調用,比如在A方法中調用了B方法,則在A調用B方法之后,必須等待B方法執行並返回后,A方法才可以繼續往下執行。這樣容易出現的一個問題就是如果B方法執行時間較長,則可能會導致調用A的請求響應遲緩,為了解決這種問題,可以使用Spirng的注解@Async來用異步調用的方式處理,當然也會有別的多線程方式解決此類問題,本文主要分析@Async在解決此類問題時的用法以及具體的示例。

異步調用

比如方法A調用方法B,如果B是一個異步方法,則A方法在調用B方法之后,不用等待B方法執行完成,而是直接往下繼續執行別的代碼。

@Async介紹

在Spring中,使用@Async標注某方法,可以使該方法變成異步方法,這些方法在被調用的時候,將會在獨立的線程中進行執行,調用者不需等待該方法執行完成。

在Spring中啟用@Async

使用@EnableAsync

@Slf4j
@SpringBootApplication
@ComponentScan(basePackages = {"com.kaesar.spring"})
@EnableAsync // 開啟異步調用
public class Application {
    public static void main(String[] args) {
        log.info("spring boot開始啟動...");
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        String[] activeProfiles = ctx.getEnvironment().getActiveProfiles();
        for (String profile : activeProfiles) {
            log.info("當前環境為:" + profile);
        }
        log.info("spring boot啟動成功...");
    }
}

示例一:基本使用方式

在方法上添加@Async注解

/**
 * 異步方法
 * 默認情況下,Spring 使用 SimpleAsyncTaskExecutor 去執行這些異步方法(此執行器沒有限制線程數)。
 * 此默認值可以從兩個層級進行覆蓋:
 * 方法級別
 * 應用級別
 */
@Async
public void test2() {
    try {
        log.info(Thread.currentThread().getName() + " in test2, before sleep.");
        Thread.sleep(2000);
        log.info(Thread.currentThread().getName() + " in test2, after sleep.");
    } catch (InterruptedException e) {
        log.error("sleep error.");
    }
}

調用異步方法

/**
 * 調用不同類的異步方法
 */
public void func1() {
    log.info("before call async function.");
    asyncService.test2();
    log.info("after call async function.");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        log.error("sleep error.");
    }
    log.info("func end.");
}

執行結果

從執行結果可以看出,main線程中的func1方法在調用異步方法test2后,沒有等待test2方法執行完成,直接執行后面的代碼。

示例二:在同一個類中調用異步方法

方法func2和上面的異步方法test2方法在同一個類中

從執行結果可知,main線程中的func2方法在調用異步方法test2方法后,等待test2方法執行完后,才繼續往后執行。

示例三:異步方法是static方法

異步方法test3是一個static方法

/**
 * 異步方法不能是 static 方法,不然注解失效
 */
@Async
public static void test3() {
  try {
    log.info(Thread.currentThread().getName() + " in test3, before sleep.");
    Thread.sleep(2000);
    log.info(Thread.currentThread().getName() + " in test3, after sleep.");
  } catch (InterruptedException e) {
    log.error("sleep error.");
  }

}

調用test3的方法

/**
 * 調用不同類的異步方法,異步方法是 static 方法
 */
public void func3() {
  log.info(Thread.currentThread().getName() + ": before call async function.");
  AsyncService.test3();
  log.info(Thread.currentThread().getName() + ": after call async function.");
  try {
    Thread.sleep(3000);
  } catch (InterruptedException e) {
    log.error("sleep error.");
  }
  log.info(Thread.currentThread().getName() + ": func end.");
}

執行結果。可以看出在static方法上添加@Async注解,當調用該方法時並沒有新啟用一個線程單獨執行,而是按順序執行代碼,說明異步無效。

示例四:在方法級別上修改默認的執行器

自定義一個線程池執行器代替默認的執行器

自定義的線程池執行器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 自定義線程池
 */
@Configuration
public class AsyncConfig {
    private static final int MAX_POOL_SIZE = 10;
    private static final int CORE_POOL_SIZE = 5;

    @Bean("asyncTaskExecutor")
    public AsyncTaskExecutor asyncTaskExecutor() {
        ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor();
        asyncTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        asyncTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        asyncTaskExecutor.setThreadNamePrefix("async-task-thread-pool-");
        asyncTaskExecutor.initialize();
        return asyncTaskExecutor;
    }
}

異步方法上使用自定義的執行器

/**
 * 在方法級別上修改默認的執行器
 */
@Async("asyncTaskExecutor")
public void test4() {
  try {
    log.info(Thread.currentThread().getName() + ": in test4, before sleep.");
    Thread.sleep(2000);
    log.info(Thread.currentThread().getName() + ": in test4, after sleep.");
  } catch (InterruptedException e) {
    log.error("sleep error.");
  }
}

調用test4異步方法

/**
 * 調用不同類的異步方法
 */
public void func4() {
  log.info(Thread.currentThread().getName() + ": before call async function.");
  asyncService.test4();
  log.info(Thread.currentThread().getName() + ": after call async function.");
  try {
    Thread.sleep(3000);
  } catch (InterruptedException e) {
    log.error("sleep error.");
  }
  log.info(Thread.currentThread().getName() + ": func end.");
}

從執行結果可以看出,@Async注解聲明使用指定的自定義的異步執行器,已經替換了默認的執行器。而且調用異步方法的main線程沒有等待異步方法的執行。

說明:新建自定義的執行器后,注解@Async默認就會替換成自定義的執行器,所以在@Async注解上可以不用指定。

\(1.01^{365} ≈ 37.7834343329\)
\(0.99^{365} ≈ 0.02551796445\)
相信堅持的力量!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM