Glide - 内存缓存与磁盘缓存

5,802 阅读4分钟

前言:

这一节我们将讲到Glide的内存缓存和磁盘缓存

(网上流传的比较广的几篇文章都是直接从是一篇译文中拷贝过去的,那篇译文在许多地方都翻译错误了,其中很大的一个错误就是关于缓存一块的问题)

Glide 系列目录

1.缓存的资源

Glide的缓存资源分为两种:

  • 1.原图(SOURCE) :原始图片
  • 2.处理图(RESULT) :经过压缩和变形等处理后的图片

2.内存缓存策略(skipMemoryCache)

Glide默认是会在内存中缓存处理图(RESULT)的.

可以通过调用skipMemoryCache(true)来设置跳过内存缓存

    //跳过内存缓存
    Glide.with(this).load(mUrl).skipMemoryCache(true).into(mIv);

调用skipMemoryCache(false)没有代码上的意义,因为Glide默认就是不跳过内存缓存的,但是显示调用这个方法,可以让别人一目了然的知道你这次请求是会在内存中缓存的,所以还是建议显示调用一下这个方法来表明你的内存缓存策略

3.磁盘缓存策略(diskCacheStrategy)

Glide磁盘缓存策略分为四种,默认的是RESULT(默认值这一点网上很多文章都写错了,但是这一点很重要):

  • 1.ALL:缓存原图(SOURCE)和处理图(RESULT)

  • 2.NONE:什么都不缓存

  • 3.SOURCE:只缓存原图(SOURCE)

  • 4.RESULT:只缓存处理图(RESULT) ---默认值

4.组合策略

和其他三级缓存一样,Glide的缓存读取顺序是 内存-->磁盘-->网络

需要注意的是Glide的内存缓存和磁盘缓存的配置相互没有直接影响,所以可以同时进行配置

例:

1.内存不缓存,磁盘缓存缓存所有图片

 Glide.with(this).load(mUrl).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.ALL).into(mIv);

2.内存缓存处理图,磁盘缓存原图

 Glide.with(this).load(mUrl).skipMemoryCache(false).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(mIv);

5.缓存大小及路径

5.1内存缓存最大空间

Glide的内存缓存其实涉及到比较多的计算,这里就介绍最重要的一个参数,就是内存缓存最大空间

内存缓存最大空间(maxSize)=每个进程可用的最大内存 * 0.4

(低配手机的话是: 每个进程可用的最大内存 * 0.33)

5.2磁盘缓存大小

磁盘缓存大小: 250 1024 1024(250MB)

/** 250 MB of cache. */
    int DEFAULT_DISK_CACHE_SIZE = 250 * 1024 * 1024;

5.3磁盘缓存目录

磁盘缓存目录: 项目/cache/image_manager_disk_cache

    String DEFAULT_DISK_CACHE_DIR = "image_manager_disk_cache";

6.清除缓存

6.1清除所有缓存

清除所有内存缓存(需要在Ui线程操作)

 Glide.get(this).clearMemory();

清除所有磁盘缓存(需要在子线程操作)

Glide.get(MainActivity.this).clearDiskCache();

注:在使用中的资源不会被清除

6.2清除单个缓存

由于Glide可能会缓存一张图片的多个分辨率的图片,并且文件名是被哈希过的,所以并不能很好的删除单个资源的缓存,以下是官方文档中的描述

Because File names are hashed keys, there is no good way to simply delete all of the cached files on disk that
correspond to a particular url or file path. The problem would be simpler if you were only ever allowed to load
or cache the original image, but since Glide also caches thumbnails and provides various transformations, each
of which will result in a new File in the cache, tracking down and deleting every cached version of an image 
is difficult.

In practice, the best way to invalidate a cache file is to change your identifier when the content changes 
(url, uri, file path etc).

热门文章