Glide的缓存机制

来源:互联网 发布:网络电玩城24小时下分 编辑:程序博客网 时间:2024/06/05 19:53

Glide缓存简介

Glide的缓存设计可以说是非常先进的,考虑的场景也很周全。在缓存这一功能上,Glide又将它分成了两个模块,一个是内存缓存,一个是硬盘缓存。

这两个缓存模块的作用各不相同,内存缓存的主要作用是防止应用重复将图片数据读取到内存当中,而硬盘缓存的主要作用是防止应用重复从网络或其他地方重复下载和读取数据。

内存缓存和硬盘缓存的相互结合才构成了Glide极佳的图片缓存效果,那么接下来我们就分别来分析一下这两种缓存的使用方法以及它们的实现原理。

缓存Key

既然是缓存功能,就必然会有用于进行缓存的Key。那么Glide的缓存Key是怎么生成的呢?我不得不说,Glide的缓存Key生成规则非常繁琐,决定缓存Key的参数竟然有10个之多。不过繁琐归繁琐,至少逻辑还是比较简单的,我们先来看一下Glide缓存Key的生成逻辑。

生成缓存Key的代码在Engine类的load()方法当中,我们现在来看一下:

public class Engine implements EngineJobListener,        MemoryCache.ResourceRemovedListener,        EngineResource.ResourceListener {    public <T, Z, R> LoadStatus load(Key signature, int width, int height, DataFetcher<T> fetcher,            DataLoadProvider<T, Z> loadProvider, Transformation<Z> transformation, ResourceTranscoder<Z, R> transcoder,            Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb) {        Util.assertMainThread();        long startTime = LogTime.getLogTime();        final String id = fetcher.getId();        EngineKey key = keyFactory.buildKey(id, signature, width, height, loadProvider.getCacheDecoder(),                loadProvider.getSourceDecoder(), transformation, loadProvider.getEncoder(),                transcoder, loadProvider.getSourceEncoder());        ...    }    ...}

可以看到,这里调用了fetcher.getId()方法获得了一个id字符串,这个字符串也就是我们要加载的图片的唯一标识,比如说如果是一张网络上的图片的话,那么这个id就是这张图片的url地址。

接下来,将这个id连同着signature、width、height等等10个参数一起传入到EngineKeyFactory的buildKey()方法当中,从而构建出了一个EngineKey对象,这个EngineKey也就是Glide中的缓存Key了。

可见,决定缓存Key的条件非常多,即使你用override()方法改变了一下图片的width或者height,也会生成一个完全不同的缓存Key。保证只有传入EngineKey的所有参数都相同的情况下才认为是同一个EngineKey对象

内存缓存

有了缓存Key,接下来就可以开始进行缓存了,那么我们先从内存缓存看起。

首先你要知道,默认情况下,Glide自动就是开启内存缓存的。也就是说,当我们使用Glide加载了一张图片之后,这张图片就会被缓存到内存当中,只要在它还没从内存中被清除之前,下次使用Glide再加载这张图片都会直接从内存当中读取,而不用重新从网络或硬盘上读取了,这样无疑就可以大幅度提升图片的加载效率。比方说你在一个RecyclerView当中反复上下滑动,RecyclerView中只要是Glide加载过的图片都可以直接从内存当中迅速读取并展示出来,从而大大提升了用户体验。

而Glide最为人性化的是,你甚至不需要编写任何额外的代码就能自动享受到这个极为便利的内存缓存功能,因为Glide默认就已经将它开启了。

那么既然已经默认开启了这个功能,还有什么可讲的用法呢?只有一点,如果你有什么特殊的原因需要禁用内存缓存功能,Glide对此提供了接口:

Glide.with(this)     .load(url)     .skipMemoryCache(true)     .into(imageView);

可以看到,只需要调用skipMemoryCache()方法并传入true,就表示禁用掉Glide的内存缓存功能。

其实说到内存缓存的实现,非常容易就让人想到LruCache算法(Least Recently Used),也叫近期最少使用算法。它的主要算法原理就是把最近使用的对象用强引用存储在LinkedHashMap中,并且把最近最少使用的对象在缓存值达到预设定值之前从内存中移除。

Glide内存缓存的实现自然也是使用的LruCache算法。不过除了LruCache算法之外,Glide还结合了一种弱引用的机制,共同完成了内存缓存功能

load()方法中,我们当时分析到了在loadGeneric()方法中会调用Glide.buildStreamModelLoader()方法来获取一个ModelLoader对象。当时没有再跟进到这个方法的里面再去分析,那么我们现在来看下它的源码:

public class Glide {    public static <T, Y> ModelLoader<T, Y> buildModelLoader(Class<T> modelClass, Class<Y> resourceClass,            Context context) {         if (modelClass == null) {            if (Log.isLoggable(TAG, Log.DEBUG)) {                Log.d(TAG, "Unable to load null model, setting placeholder only");            }            return null;        }        return Glide.get(context).getLoaderFactory().buildModelLoader(modelClass, resourceClass);    }    public static Glide get(Context context) {        if (glide == null) {            synchronized (Glide.class) {                if (glide == null) {                    Context applicationContext = context.getApplicationContext();                    List<GlideModule> modules = new ManifestParser(applicationContext).parse();                    GlideBuilder builder = new GlideBuilder(applicationContext);                    for (GlideModule module : modules) {                        module.applyOptions(applicationContext, builder);                    }                    glide = builder.createGlide();                    for (GlideModule module : modules) {                        module.registerComponents(applicationContext, glide);                    }                }            }        }        return glide;    }    ...}

构建ModelLoader对象的时候,先调用了一个Glide.get()方法,而这个方法就是关键。我们可以看到,get()方法中实现的是一个单例功能,而创建Glide对象则是调用GlideBuilder的createGlide()方法来创建的,那么我们跟到这个方法当中:

public class GlideBuilder {    ...    Glide createGlide() {        if (sourceService == null) {            final int cores = Math.max(1, Runtime.getRuntime().availableProcessors());            sourceService = new FifoPriorityThreadPoolExecutor(cores);        }        if (diskCacheService == null) {            diskCacheService = new FifoPriorityThreadPoolExecutor(1);        }        MemorySizeCalculator calculator = new MemorySizeCalculator(context);        if (bitmapPool == null) {            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {                int size = calculator.getBitmapPoolSize();                bitmapPool = new LruBitmapPool(size);            } else {                bitmapPool = new BitmapPoolAdapter();            }        }        if (memoryCache == null) {        //22行            memoryCache = new LruResourceCache(calculator.getMemoryCacheSize());        }        if (diskCacheFactory == null) {            diskCacheFactory = new InternalCacheDiskCacheFactory(context);        }        if (engine == null) {            engine = new Engine(memoryCache, diskCacheFactory, diskCacheService, sourceService);        }        if (decodeFormat == null) {            decodeFormat = DecodeFormat.DEFAULT;        }        return new Glide(engine, memoryCache, bitmapPool, context, decodeFormat);    }}

这里也就是构建Glide对象的地方了。那么观察22行,你会发现这里new出了一个LruResourceCache,并把它赋值到了memoryCache这个对象上面。你没有猜错,这个就是Glide实现内存缓存所使用的LruCache对象了。

现在创建好了LruResourceCache对象只能说是把准备工作做好了,接下来我们就一步步研究Glide中的内存缓存到底是如何实现的。
刚才在Engine的load()方法中我们已经看到了生成缓存Key的代码,而内存缓存的代码其实也是在这里实现的,那么我们重新来看一下Engine类load()方法的完整源码:

public class Engine implements EngineJobListener,        MemoryCache.ResourceRemovedListener,        EngineResource.ResourceListener {    ...        public <T, Z, R> LoadStatus load(Key signature, int width, int height, DataFetcher<T> fetcher,            DataLoadProvider<T, Z> loadProvider, Transformation<Z> transformation, ResourceTranscoder<Z, R> transcoder,            Priority priority, boolean isMemoryCacheable, DiskCacheStrategy diskCacheStrategy, ResourceCallback cb) {        Util.assertMainThread();        long startTime = LogTime.getLogTime();        final String id = fetcher.getId();        EngineKey key = keyFactory.buildKey(id, signature, width, height, loadProvider.getCacheDecoder(),                loadProvider.getSourceDecoder(), transformation, loadProvider.getEncoder(),                transcoder, loadProvider.getSourceEncoder());        //loadFromCache        EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);        if (cached != null) {            cb.onResourceReady(cached);            if (Log.isLoggable(TAG, Log.VERBOSE)) {                logWithTimeAndKey("Loaded resource from cache", startTime, key);            }            return null;        }        //loadFromActiveResources        EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);        if (active != null) {            cb.onResourceReady(active);            if (Log.isLoggable(TAG, Log.VERBOSE)) {                logWithTimeAndKey("Loaded resource from active resources", startTime, key);            }            return null;        }        EngineJob current = jobs.get(key);        if (current != null) {            current.addCallback(cb);            if (Log.isLoggable(TAG, Log.VERBOSE)) {                logWithTimeAndKey("Added to existing load", startTime, key);            }            return new LoadStatus(cb, current);        }        EngineJob engineJob = engineJobFactory.build(key, isMemoryCacheable);        DecodeJob<T, Z, R> decodeJob = new DecodeJob<T, Z, R>(key, width, height, fetcher, loadProvider, transformation,                transcoder, diskCacheProvider, diskCacheStrategy, priority);        EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority);        jobs.put(key, engineJob);        engineJob.addCallback(cb);        engineJob.start(runnable);        if (Log.isLoggable(TAG, Log.VERBOSE)) {            logWithTimeAndKey("Started new load", startTime, key);        }        return new LoadStatus(cb, engineJob);    }    ...}

可以看到,这里调用了loadFromCache()方法来获取缓存图片,如果获取到就直接调用cb.onResourceReady()方法进行回调。如果没有获取到,则会调用loadFromActiveResources()方法来获取缓存图片,获取到的话也直接进行回调。只有在两个方法都没有获取到缓存的情况下,才会继续向下执行,从而开启线程来加载图片。

也就是说,Glide的图片加载过程中会调用两个方法来获取内存缓存,loadFromCache()loadFromActiveResources()。这两个方法中一个使用的就是LruCache算法,另一个使用的就是弱引用。

public class Engine implements EngineJobListener,        MemoryCache.ResourceRemovedListener,        EngineResource.ResourceListener {    private final MemoryCache cache;    private final Map<Key, WeakReference<EngineResource<?>>> activeResources;    ...    private EngineResource<?> loadFromCache(Key key, boolean isMemoryCacheable) {        if (!isMemoryCacheable) {            return null;        }        EngineResource<?> cached = getEngineResourceFromCache(key);        if (cached != null) {            cached.acquire();            activeResources.put(key, new ResourceWeakReference(key, cached, getReferenceQueue()));        }        return cached;    }    private EngineResource<?> getEngineResourceFromCache(Key key) {        Resource<?> cached = cache.remove(key);        final EngineResource result;        if (cached == null) {            result = null;        } else if (cached instanceof EngineResource) {            result = (EngineResource) cached;        } else {            result = new EngineResource(cached, true /*isCacheable*/);        }        return result;    }    private EngineResource<?> loadFromActiveResources(Key key, boolean isMemoryCacheable) {        if (!isMemoryCacheable) {            return null;        }        EngineResource<?> active = null;        WeakReference<EngineResource<?>> activeRef = activeResources.get(key);        if (activeRef != null) {            active = activeRef.get();            if (active != null) {                active.acquire();            } else {                activeResources.remove(key);            }        }        return active;    }    ...}

在loadFromCache()方法的一开始,首先就判断了isMemoryCacheable是不是false,如果是false的话就直接返回null。这是什么意思呢?其实很简单,我们刚刚不是学了一个skipMemoryCache()方法吗?如果在这个方法中传入true,那么这里的isMemoryCacheable就会是false,表示内存缓存已被禁用。

我们继续住下看,接着调用了getEngineResourceFromCache()方法来获取缓存。在这个方法中,会使用缓存Key来从cache当中取值,而这里的cache对象就是在构建Glide对象时创建的LruResourceCache,那么说明这里其实使用的就是LruCache算法了。

但是呢,当我们从LruResourceCache中获取到缓存图片之后会将它(getEngineResourceFromCache)从缓存中移除,然后在loadFromCache将这个缓存图片存储到activeResources当中。activeResources就是一个弱引用的HashMap,用来缓存正在使用中的图片,我们可以看到,loadFromActiveResources()方法就是从activeResources这个HashMap当中取值的。使用activeResources来缓存正在使用中的图片,可以保护这些图片不会被LruCache算法回收掉。

好的,从内存缓存中读取数据的逻辑大概就是这些了。概括一下来说,就是如果能从内存缓存当中读取到要加载的图片,那么就直接进行回调,如果读取不到的话,才会开启线程执行后面的图片加载逻辑。

硬盘缓存

为了禁止Glide对图片进行硬盘缓存而使用了如下代码:

Glide.with(this)     .load(url)     .diskCacheStrategy(DiskCacheStrategy.NONE)     .into(imageView);

调用diskCacheStrategy()方法并传入DiskCacheStrategy.NONE,就可以禁用掉Glide的硬盘缓存功能了。

这个diskCacheStrategy()方法基本上就是Glide硬盘缓存功能的一切,它可以接收四种参数:

  • DiskCacheStrategy.NONE: 表示不缓存任何内容。
  • DiskCacheStrategy.SOURCE: 表示只缓存原始图片。
  • DiskCacheStrategy.RESULT: 表示只缓存转换过后的图片(默认选项)。
  • DiskCacheStrategy.ALL : 表示既缓存原始图片,也缓存转换过后的图片。

上面四种参数的解释本身并没有什么难理解的地方,但是有一个概念大家需要了解,就是当我们使用Glide去加载一张图片的时候,Glide默认并不会将原始图片展示出来,而是会对图片进行压缩和转换(我们会在后面学习这方面的内容)。总之就是经过种种一系列操作之后得到的图片,就叫转换过后的图片。而Glide默认情况下在硬盘缓存的就是转换过后的图片,我们通过调用diskCacheStrategy()方法则可以改变这一默认行为。

阅读全文
0 0