flowable源碼解讀之LRU緩存設(shè)計(jì)

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

1. 用戶定義的入口

先回顧一下,如果我們要在Spring環(huán)境中使用flowable必須采用類似方式定義一個(gè)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定義中可以設(shè)置processDefinitionCacheLimit等屬性的值即可控制緩存的容量,如果沒有進(jìn)行設(shè)置將不會(huì)對其限制,為以防止OOM異常,建議可以設(shè)置一個(gè),當(dāng)超出容量時(shí)flowable引擎將會(huì)通過LRU算法進(jìn)行移除。

2. 緩存的初始化

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

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

以initProcessDefinitionCache為例看一下方法實(shí)現(xiàn),不用多說:

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

進(jìn)入DefaultDeploymentCache的構(gòu)造方法,當(dāng)沒有設(shè)置緩存大小時(shí)通過無參構(gòu)造方法創(chuàng)建的是一個(gè)同步的Map, 重點(diǎn)可以看一下下面的有參構(gòu)造函數(shù)實(shí)現(xiàn):

/** 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;
        }

    });
}

有參構(gòu)造方法核心是基于LinkedHashMap并且重寫了removeEldestEntry方法,當(dāng)超出容量時(shí)會(huì)返回true, 查看LinkedHashMap可以知道當(dāng)調(diào)用put或putAll返回前會(huì)根據(jù)該方法返回的值決定是否移除最老的一個(gè)元素,從而實(shí)現(xiàn)了LRU緩存算法。

3. 緩存的寫入與更新

在流程部署時(shí)肯定會(huì)涉及到相關(guān)數(shù)據(jù)的更新,通過RepositoryServiceImpl.deploy->DeployCmd.executeDeploy查看有如下代碼:

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

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

        cachingAndArtifactsManager.updateCachingAndArtifacts(parsedDeployment);

然后想看CachingAndArtifactsManager.updateCachingAndArtifacts方法源碼即具體更新緩存的實(shí)現(xiàn):

    /**
     * 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. 緩存的讀取

一個(gè)典型的讀取場景就是在啟動(dòng)流程的時(shí)候,所以查看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);
    }

}

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

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方法, 當(dāng)緩存中沒有數(shù)據(jù)時(shí)會(huì)調(diào)用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;
}

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,725評論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,695評論 2 370