flowable源碼解讀之LRU緩存設計

流程數據的定義在flowable中是比較復雜的, 涉及到多張數據庫表關聯關系,這些在一個流程引擎中也是最為核心的數據,并且需要進行頻繁的讀取,所以為了實現讀取的高效性,flowable將流程定義的數據放在內存中,需要時直接從內存中獲取。本文就簡單看一看flowable是怎么實現緩存的。

1. 用戶定義的入口

先回顧一下,如果我們要在Spring環境中使用flowable必須采用類似方式定義一個bean

<bean id="processEngineConfiguration"
      class="org.flowable.spring.SpringProcessEngineConfiguration">

SpringProcessEngineConfiguration繼承于ProcessEngineConfigurationImpl,在ProcessEngineConfigurationImpl源碼中可以看到:

    protected int processDefinitionCacheLimit = -1; // By default, no limit
    protected DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache;

    protected int processDefinitionInfoCacheLimit = -1; // By default, no limit
    protected ProcessDefinitionInfoCache processDefinitionInfoCache;

    protected int knowledgeBaseCacheLimit = -1;
    protected DeploymentCache<Object> knowledgeBaseCache;

    protected int appResourceCacheLimit = -1;
    protected DeploymentCache<Object> appResourceCache;

因此我們可以在bean定義中可以設置processDefinitionCacheLimit等屬性的值即可控制緩存的容量,如果沒有進行設置將不會對其限制,為以防止OOM異常,建議可以設置一個,當超出容量時flowable引擎將會通過LRU算法進行移除。

2. 緩存的初始化

flowable流程引擎在Spring環境中的啟動源碼分析這篇文章我們已經知道了flowble流程的初始化過程,那么對緩存的初始化肯定也能在相關內里找到,在ProcessEngineConfigurationImpl的init方法中有如下幾行代碼:

        initProcessDefinitionCache();
        initProcessDefinitionInfoCache();
        initAppResourceCache();
        initKnowledgeBaseCache();

以initProcessDefinitionCache為例看一下方法實現,不用多說:

    public void initProcessDefinitionCache() {
        if (processDefinitionCache == null) {
            if (processDefinitionCacheLimit <= 0) {
                processDefinitionCache = new DefaultDeploymentCache<ProcessDefinitionCacheEntry>();
            } else {
                processDefinitionCache = new DefaultDeploymentCache<ProcessDefinitionCacheEntry>(processDefinitionCacheLimit);
            }
        }
    }

進入DefaultDeploymentCache的構造方法,當沒有設置緩存大小時通過無參構造方法創建的是一個同步的Map, 重點可以看一下下面的有參構造函數實現:

/** Cache with no limit */
public DefaultDeploymentCache() {
    this.cache = Collections.synchronizedMap(new HashMap<String, T>());
}

/**
 * Cache which has a hard limit: no more elements will be cached than the limit.
 */
public DefaultDeploymentCache(final int limit) {
    this.cache = Collections.synchronizedMap(new LinkedHashMap<String, T>(limit + 1, 0.75f, true) { // +1 is needed, because the entry is inserted first, before it is removed
        // 0.75 is the default (see javadocs)
        // true will keep the 'access-order', which is needed to have a real LRU cache
        private static final long serialVersionUID = 1L;

        protected boolean removeEldestEntry(Map.Entry<String, T> eldest) {
            boolean removeEldest = size() > limit;
            if (removeEldest && logger.isTraceEnabled()) {
                logger.trace("Cache limit is reached, {} will be evicted", eldest.getKey());
            }
            return removeEldest;
        }

    });
}

有參構造方法核心是基于LinkedHashMap并且重寫了removeEldestEntry方法,當超出容量時會返回true, 查看LinkedHashMap可以知道當調用put或putAll返回前會根據該方法返回的值決定是否移除最老的一個元素,從而實現了LRU緩存算法。

3. 緩存的寫入與更新

在流程部署時肯定會涉及到相關數據的更新,通過RepositoryServiceImpl.deploy->DeployCmd.executeDeploy查看有如下代碼:

        // Actually deploy
        commandContext.getProcessEngineConfiguration().getDeploymentManager().deploy(deployment, deploymentSettings);

查看DeploymentManager.deploy->BpmnDeployer.deploy代碼:

        cachingAndArtifactsManager.updateCachingAndArtifacts(parsedDeployment);

然后想看CachingAndArtifactsManager.updateCachingAndArtifacts方法源碼即具體更新緩存的實現:

    /**
     * Ensures that the process definition is cached in the appropriate places, including the deployment's collection of deployed artifacts and the deployment manager's cache, as well as caching any
     * ProcessDefinitionInfos.
     */
    public void updateCachingAndArtifacts(ParsedDeployment parsedDeployment) {
        CommandContext commandContext = Context.getCommandContext();
        final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
        DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache = processEngineConfiguration.getDeploymentManager().getProcessDefinitionCache();
        DeploymentEntity deployment = parsedDeployment.getDeployment();

        for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
            BpmnModel bpmnModel = parsedDeployment.getBpmnModelForProcessDefinition(processDefinition);
            Process process = parsedDeployment.getProcessModelForProcessDefinition(processDefinition);
            ProcessDefinitionCacheEntry cacheEntry = new ProcessDefinitionCacheEntry(processDefinition, bpmnModel, process);
            processDefinitionCache.add(processDefinition.getId(), cacheEntry);
            addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);

            // Add to deployment for further usage
            deployment.addDeployedArtifact(processDefinition);
        }
    }

4. 緩存的讀取

一個典型的讀取場景就是在啟動流程的時候,所以查看RuntimeServiceImpl.startProcessInstanceByKey->StartProcessInstanceCmd.execute方法源碼:

// Find the process definition
ProcessDefinition processDefinition = null;
if (processDefinitionId != null) {

    processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
    if (processDefinition == null) {
        throw new FlowableObjectNotFoundException("No process definition found for id = '" + processDefinitionId + "'", ProcessDefinition.class);
    }

}

接下來進入DeploymentManager.findDeployedProcessDefinitionById可以看到, 首先會從緩存中查找,如果沒有則從數據庫中加載:

public ProcessDefinition findDeployedProcessDefinitionById(String processDefinitionId) {
    if (processDefinitionId == null) {
        throw new FlowableIllegalArgumentException("Invalid process definition id : null");
    }

    // first try the cache
    ProcessDefinitionCacheEntry cacheEntry = processDefinitionCache.get(processDefinitionId);
    ProcessDefinition processDefinition = cacheEntry != null ? cacheEntry.getProcessDefinition() : null;

    if (processDefinition == null) {
        processDefinition = processDefinitionEntityManager.findById(processDefinitionId);
        if (processDefinition == null) {
            throw new FlowableObjectNotFoundException("no deployed process definition found with id '" + processDefinitionId + "'", ProcessDefinition.class);
        }
        processDefinition = resolveProcessDefinition(processDefinition).getProcessDefinition();
    }
    return processDefinition;
}

然后看一下resolveProcessDefinition方法, 當緩存中沒有數據時會調用deploy方法來重新加載緩存。

/**
 * Resolving the process definition will fetch the BPMN 2.0, parse it and store the {@link BpmnModel} in memory.
 */
public ProcessDefinitionCacheEntry resolveProcessDefinition(ProcessDefinition processDefinition) {
    String processDefinitionId = processDefinition.getId();
    String deploymentId = processDefinition.getDeploymentId();

    ProcessDefinitionCacheEntry cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);

    if (cachedProcessDefinition == null) {
        if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, processEngineConfiguration)) {
            return Flowable5Util.getFlowable5CompatibilityHandler().resolveProcessDefinition(processDefinition);
        }

        DeploymentEntity deployment = deploymentEntityManager.findById(deploymentId);
        deployment.setNew(false);
        deploy(deployment, null);
        cachedProcessDefinition = processDefinitionCache.get(processDefinitionId);

        if (cachedProcessDefinition == null) {
            throw new FlowableException("deployment '" + deploymentId + "' didn't put process definition '" + processDefinitionId + "' in the cache");
        }
    }
    return cachedProcessDefinition;
}

總結一下:flowable緩存的實現核心即基于LinkedHashMap并通過重寫其removeEldestEntry方法實現LRU緩存移除算法。以流程定義緩存為例可以知道,每次部署時會將流程定義的數據加入緩存,每次流程啟動時都會嘗試去緩存中獲取數據,如果緩存中有就直接返回,如果沒有就從數據庫中加載并放入緩存以供下次使用。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。