Application startup acceleration: Asynchronous initialization
SOFABoot accelerates application startup in two ways:
Asynchronously executes the bean's initialization method
This topic describes how to use SOFABoot to asynchronously execute the initialization method of a bean to accelerate application startup.
Principle of asynchronous acceleration
In actual Spring/Spring Boot development, some beans perform some preparation operations during initialization, such as:
Pull remote configuration
Initialize a data source
During application startup, these beans increase the Spring context refresh time, resulting in a longer application startup duration.
To accelerate application startup, SOFABoot uses a separate thread to asynchronously execute the Bean initialization method (init-method) by configuring an option. This accelerates the Spring context loading process and improves application startup speed.
Asynchronous acceleration implementation
The principle of asynchronous bean initialization is to open a separate thread responsible for executing the bean's initialization method (init-method). An example of the implementation steps is as follows:
Introduce dependencies: Introduce the following starter into the
pom.xmlfile of the project:<dependency> <groupId>com.alipay.sofa</groupId> <artifactId>runtime-sofa-boot-starter</artifactId> </dependency>XML configuration: Configure the
async-init="true"attribute in the XML of the bean to specify whether to execute the initialization method of the bean asynchronously. The configuration method is shown in the following example.<?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.xsd http://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" async-init="true"/> </beans>Attribute configuration: specifies the size of the asynchronous initialization capability of SOFABoot. This value is reflected by configuring the size of the thread pool. The thread pool is used to asynchronously execute bean initialization methods (init-method). The property values of the thread pool can be configured by using one of the following methods.
is specified by two properties in the
application.properties.com.alipay.sofa.boot.asyncInitBeanCoreSize: the basic size of the thread pool. The default value is the number of CPU cores plus one.com.alipay.sofa.boot.asyncInitBeanMaxSize: the maximum number of threads allowed in the thread pool. The default value is the number of CPU cores plus one.
Set by
VM -Dparameters.