ExoPlayer的缓存 三 SimpleCache的使用

ExoPlayer的缓存 – 三 Cache的使用


在这里插入图片描述

CacheDataSource 读取数据

创建 CacheDataSource

和 exoplayer 的其他 DataSource 一样,CacheDataSource 的生成也是通过 Factory 模式生成,

  private CacheDataSource createDataSourceInternal(
      @Nullable DataSource upstreamDataSource, @Flags int flags, int upstreamPriority) {
   
    Cache cache = checkNotNull(this.cache);
    @Nullable DataSink cacheWriteDataSink;
    if (cacheIsReadOnly || upstreamDataSource == null) {
   
      cacheWriteDataSink = null;
    } else if (cacheWriteDataSinkFactory != null) {
   
      cacheWriteDataSink = cacheWriteDataSinkFactory.createDataSink();
    } else {
   
      cacheWriteDataSink = new CacheDataSink.Factory().setCache(cache).createDataSink();
    }
    return new CacheDataSource(
        cache,
        upstreamDataSource,
        cacheReadDataSourceFactory.createDataSource(),
        cacheWriteDataSink,
        cacheKeyFactory,
        flags,
        upstreamPriorityTaskManager,
        upstreamPriority,
        eventListener);
  }
}

CacheDataSource 构造函数的参数和读写有关的有

  1. Cache cache 使用的缓存

  2. @Nullable DataSource upstreamDataSource 根据url 生成的 DataSource, 可为null, 只能从Cache 中读取数据

  3. cacheReadDataSource 从cache 中读取数据用的 DataSource

  4. @Nullable DataSink cacheWriteDataSink 写缓存用的DataSink,可为null, 不可向Cache 中写数据

  5. @Nullable CacheKeyFactory cacheKeyFactory 用来生成 Cache ID, 用来匹配Cache

private CacheDataSource(
    Cache cache,
    @Nullable DataSource upstreamDataSource,
    DataSource cacheReadDataSource,
    @Nullable DataSink cacheWriteDataSink,
    @Nullable CacheKeyFactory cacheKeyFactory,
    ......
) {
   
  ......
      this.upstreamDataSource = upstreamDataSource;
      this.cacheWriteDataSource =
          cacheWriteDataSink != null
              ? new TeeDataSource(upstreamDataSource, cacheWriteDataSink)
              : null;
}

在 CacheDataSource 的构造函数中 通过 upstreamDataSourcecacheWriteDataSink 生成cacheWriteDataSource 类型为TeeDataSource。 缓存的保存正是通过TeeDataSource 完成。

TeeDataSource 写入缓存数据

在TeeDataSource 的read 函数中,先从upstream 中 读取数据,然后写入到dataSink 中。

public int read(byte[] buffer, int offset, int length) throws IOException {
   
  if (bytesRemaining == 0) {
   
    return C.RESULT_END_OF_INPUT;
  }
  int bytesRead = upstream.read(buffer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值