Elasticsearch中fielddata_cache的實(shí)現(xiàn)

背景

????基于一次fielddata_cache(容量還沒到閾值)被逐出后,想具體了解fielddata_cache的實(shí)現(xiàn)來判斷fielddata數(shù)據(jù)是否是常駐內(nèi)存亦或是只是個(gè)軟、弱引用,本文基于v1.0.0版本。


實(shí)現(xiàn)

????我們直接從Elasticsearch.java這個(gè)啟動(dòng)類開始往下看:

Elasticsearch.java {
    public static void main(String[] args) {
        Bootstrap.main(args);
    }
}

????Elasticsearch通過Bootstrap類來啟動(dòng),具體再看Bootstrap的實(shí)現(xiàn),忽略一些代碼,我們來Bootstrap的實(shí)例化和初始化:

Bootstrap.java {
    public static void main(String[] args) {
     
        bootstrap = new Bootstrap();
 
        Tuple<Settings, Environment> tuple = null; //我們的一些配置
        try {
            tuple = initialSettings();
            setupLogging(tuple);
        } catch (Exception e) {
            ...
        }
 
        try {
         
            bootstrap.setup(true, tuple);
 
            ...
        } catch (Throwable e) {
                ...
        }
    }
}

????Bootstrap的setup()會(huì)創(chuàng)建我們的Elasticsearch的節(jié)點(diǎn)實(shí)例:

Bootstrap.java {
  
    private Node node;
  
    private void setup(boolean addShutdownHook, Tuple<Settings, Environment> tuple) throws Exception {
 
        NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder().settings(tuple.v1()).loadConfigSettings(false);
        node = nodeBuilder.build();
        ...       
    }
  
}

????NodeBuilder會(huì)創(chuàng)建一個(gè)InternalNode實(shí)例,我們InternalNode的初始化,重點(diǎn)看到我們會(huì)添加一個(gè)IndicesModule:

InternalNode.java {
     
    public InternalNode(Settings pSettings, boolean loadConfigSettings) throws ElasticsearchException {
 
        logger.info("initializing ...");
         
        ...
 
        ModulesBuilder modules = new ModulesBuilder();
     
        modules.add(new IndicesModule(settings));
         
        ...
 
        logger.info("initialized");
    }
}

????再接著看IndicesModule的實(shí)現(xiàn),我們通過綁定IndicesFieldDataCache類來實(shí)現(xiàn)索引級(jí)別的fielddata_cache:

IndicesModule.java {
  
    protected void configure() {
        ...
        bind(IndicesFieldDataCache.class).asEagerSingleton();
        ...
    }
}

????重點(diǎn)來看IndicesFieldDataCache的實(shí)現(xiàn),從下面代碼可以看到Elasticsearch通過guava的CacheBuilder來實(shí)現(xiàn)索引級(jí)別的fielddata_cache,具體的CacheBuilder介紹可以自行查閱一下:

IndicesFieldDataCache.java {
 
    Cache<Key, AtomicFieldData> cache;
 
    private volatile String size;
    private volatile long sizeInBytes;
    private volatile TimeValue expire;
 
    @Inject
    public IndicesFieldDataCache(Settings settings) {
        super(settings);
        this.size = componentSettings.get("size", "-1"); //indices.fielddata.cache.size的大小
        this.sizeInBytes = componentSettings.getAsMemory("size", "-1").bytes(); //indices.fielddata.cache.size的大小
        this.expire = componentSettings.getAsTime("expire", null); //indices.fielddata.cache.expire的大小
        buildCache();
    }
 
    private void buildCache() {
        CacheBuilder<Key, AtomicFieldData> cacheBuilder = CacheBuilder.newBuilder()
                .removalListener(this);
        if (sizeInBytes > 0) { //設(shè)置LRU的閾值
            cacheBuilder.maximumWeight(sizeInBytes).weigher(new FieldDataWeigher());
        }
         
        cacheBuilder.concurrencyLevel(16);
        if (expire != null && expire.millis() > 0) { //設(shè)置Cache的過期時(shí)間
            cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
        }
        logger.debug("using size [{}] [{}], expire [{}]", size, new ByteSizeValue(sizeInBytes), expire);
        cache = cacheBuilder.build();
    }
 
    ...
} 

????最后再看CacheBuilder是怎么被使用的(默認(rèn)情況下CacheBuilder的key和value都是強(qiáng)引用的),IndicesFieldDataCache在給上層提供實(shí)現(xiàn)時(shí)是返回了一個(gè)IndexFieldCache,可以看到在需要load索引的fielddata_cache時(shí)通過CacheBuilder在get時(shí)候的原則"獲取緩存-如果沒有-則計(jì)算"實(shí)現(xiàn):

IndexFieldCache.java {
 
    @Nullable
    private final IndexService indexService;
    final Index index;
    final FieldMapper.Names fieldNames;
    final FieldDataType fieldDataType;
 
    IndexFieldCache(@Nullable IndexService indexService, Index index, FieldMapper.Names fieldNames, FieldDataType fieldDataType) {
        this.indexService = indexService;
        this.index = index;
        this.fieldNames = fieldNames;
        this.fieldDataType = fieldDataType;
    }
 
    @Override
    public <FD extends AtomicFieldData, IFD extends IndexFieldData<FD>> FD load(final AtomicReaderContext context, final IFD indexFieldData) throws Exception {
        final Key key = new Key(this, context.reader().getCoreCacheKey());
         
        return (FD) cache.get(key, new Callable<AtomicFieldData>() {
            @Override
            public AtomicFieldData call() throws Exception {
                SegmentReaderUtils.registerCoreListener(context.reader(), IndexFieldCache.this);
                AtomicFieldData fieldData = indexFieldData.loadDirect(context);
 
                ...
 
                return fieldData;
            }
        });
    }
 
}

總結(jié)

????簡(jiǎn)單介紹了Elasticsearch-1.0.0版本fielddata_cache的實(shí)現(xiàn),經(jīng)過分析知道fielddata_cache默認(rèn)是強(qiáng)引用對(duì)象,所以只存在LRU并不會(huì)被GC掉,至于為啥會(huì)被逐出還需要再看看指標(biāo)怎么統(tǒng)計(jì)的。


(個(gè)人分析,有錯(cuò)誤請(qǐng)指正)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容