前言
大家好,我是老馬。
sofastack 其實出來很久了,第一次應該是在 2022 年左右開始關注,但是一直沒有深入研究。
最近想學習一下 SOFA 對于生態的設計和思考。
sofaboot 系列
SOFABoot-00-sofaboot 概覽
SOFABoot-01-螞蟻金服開源的 sofaboot 是什么黑科技?
SOFABoot-02-模塊化隔離方案
SOFABoot-03-sofaboot 介紹
SOFABoot-04-快速開始
SOFABoot-05-依賴管理
SOFABoot-06-健康檢查
SOFABoot-07-版本查看
SOFABoot-08-啟動加速
SOFABoot-09-模塊隔離
SOFABoot-10-聊一聊 sofatboot 的十個問題
啟動加速
SOFABoot 提供了模塊并行加載以及 Spring Bean 異步初始化能力,用于加快應用啟動速度。
模塊并行加載參考相應文檔,下面介紹如何使用 SOFABoot 異步初始化 Spring Bean 能力來提高應用啟動速度。
引入依賴
SOFABoot 在 v2.6.0 開始提供異步初始化 Spring Bean 能力,引入如下 Starter 即可:
<dependency><groupId>com.alipay.sofa</groupId><artifactId>runtime-sofa-boot-starter</artifactId>
</dependency>
使用場景
在實際使用 Spring/Spring Boot 開發中,會有一些 Bean 在初始化過程中執行準備操作,如拉取遠程配置、初始化數據源等等;
在應用啟動期間,這類 Bean 會增加 Spring 上下文刷新時間,導致應用啟動耗時變長。
為了加速應用啟動,SOFABoot 通過配置可選項,將 Bean 的初始化方法(init-method) 使用單獨線程異步執行,加快 Spring 上下文加載過程,提高應用啟動速度。
使用方法
異步初始化 Bean 的原理是開啟單獨線程負責執行 Bean 的初始化方法(init-method),因此在使用過程中,除了引入上述依賴管理,還需要在 Bean 的 xml 定義中配置 sofa:async-init=“true” 屬性,用于指定是否異步執行該 Bean 的初始化方法,例如:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:sofa="http://sofastack.io/schema/sofaboot"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://sofastack.io/schema/sofaboot http://sofastack.io/schema/sofaboot.xsd"default-autowire="byName"><!-- async init test --><bean id="testBean" class="com.alipay.sofa.runtime.beans.TimeWasteBean" init-method="init" sofa:async-init="true"/>
</beans>
配置
SOFABoot 異步初始化能力提供兩個屬性配置,用于指定負責異步執行 Bean 初始化方法(init-method)的線程池大小:
- com.alipay.sofa.boot.asyncInitBeanCoreSize > 線程池基本大小,默認值為 CPU 核數加一 + com.alipay.sofa.boot.asyncInitBeanMaxSize > 線程池中允許的最大線程數大小,默認值為 CPU 核數加一
配置可以通過 VM -D 參數或者 Spring Boot 配置文件 application.yml 設置。
小結
希望本文對你有所幫助,如果喜歡,歡迎點贊收藏轉發一波。
我是老馬,期待與你的下次相遇。