RxCache.java 11.7 KB
Newer Older
konghaorui committed
1 2 3 4
package com.ydl.ydlnet.cache;

import android.os.Environment;
import android.os.StatFs;
YKai committed
5
import androidx.annotation.NonNull;
konghaorui committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
import com.ydl.ydlnet.cache.data.CacheResult;
import com.ydl.ydlnet.cache.diskconverter.IDiskConverter;
import com.ydl.ydlnet.cache.diskconverter.SerializableDiskConverter;
import com.ydl.ydlnet.cache.stategy.IFlowableStrategy;
import com.ydl.ydlnet.cache.stategy.IObservableStrategy;
import com.ydl.ydlnet.cache.utils.RxCacheLogUtils;
import io.reactivex.*;
import org.reactivestreams.Publisher;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.security.MessageDigest;


/**
 * RxJava remote data cache processing library, support Serializable, JSON
 * 作者: 赵成柱 on 2016/9/9 0012.
 */
public final class RxCache {


    private final CacheCore cacheCore;

    private static RxCache sDefaultRxCache;

    @NonNull
    public static RxCache getDefault() {
        if (sDefaultRxCache == null) {
            sDefaultRxCache = new Builder()
                    .appVersion(1)
                    .diskDir(Environment.getDownloadCacheDirectory())
                    .diskConverter(new SerializableDiskConverter())
                    .setDebug(true)
                    .build();

        }
        return sDefaultRxCache;
    }

    public static void initializeDefault(RxCache rxCache) {
        if (sDefaultRxCache == null) {
            RxCache.sDefaultRxCache = rxCache;
        } else {
            RxCacheLogUtils.log("You need to initialize it before using the default rxCache and only initialize it once");
        }
    }


    private RxCache(Builder builder) {
        LruMemoryCache memoryCache = null;
        if (builder.memoryMaxSize > 0) {
            memoryCache = new LruMemoryCache(builder.memoryMaxSize);
        }
        LruDiskCache lruDiskCache = null;
        if (builder.diskMaxSize > 0) {
            lruDiskCache = new LruDiskCache(builder.diskConverter, builder.diskDir, builder.appVersion, builder.diskMaxSize);
        }
        cacheCore = new CacheCore(memoryCache, lruDiskCache);

    }

    /**
     * notice: Deprecated! Use {@link #transformObservable(String, Type, IObservableStrategy)} ()}  replace.
     */
    @Deprecated
    public <T> ObservableTransformer<T, CacheResult<T>> transformer(String key, Type type, IObservableStrategy strategy) {
        return transformObservable(key, type, strategy);
    }

    public <T> ObservableTransformer<T, CacheResult<T>> transformObservable(final String key, final Type type, final IObservableStrategy strategy) {
        return new ObservableTransformer<T, CacheResult<T>>() {
            @Override
            public ObservableSource<CacheResult<T>> apply(Observable<T> tObservable) {
                return strategy.execute(RxCache.this, key, tObservable, type);
            }
        };
    }

    public <T> FlowableTransformer<T, CacheResult<T>> transformFlowable(final String key, final Type type, final IFlowableStrategy strategy) {
        return new FlowableTransformer<T, CacheResult<T>>() {
            @Override
            public Publisher<CacheResult<T>> apply(Flowable<T> flowable) {
                return strategy.flow(RxCache.this, key, flowable, type);
            }
        };
    }


    /**
     * 读取
     */
    public <T> Observable<CacheResult<T>> load(final String key, final Type type) {
        return Observable.create(new ObservableOnSubscribe<CacheResult<T>>() {
            @Override
            public void subscribe(ObservableEmitter<CacheResult<T>> observableEmitter) throws Exception {
                CacheResult<T> load = cacheCore.load(getMD5MessageDigest(key), type);
                if (!observableEmitter.isDisposed()) {
                    if (load != null) {
                        observableEmitter.onNext(load);
                        observableEmitter.onComplete();
                    } else {
                        observableEmitter.onError(new NullPointerException("Not find the key corresponding to the cache"));
                    }
                }
            }
        });
    }

    /**
     * 读取
     */
    public <T> Flowable<CacheResult<T>> load2Flowable(String key, Type type) {
        return load2Flowable(key, type, BackpressureStrategy.LATEST);
    }

    public <T> Flowable<CacheResult<T>> load2Flowable(final String key, final Type type, BackpressureStrategy backpressureStrategy) {
        return Flowable.create(new FlowableOnSubscribe<CacheResult<T>>() {
            @Override
            public void subscribe(FlowableEmitter<CacheResult<T>> flowableEmitter) throws Exception {
                CacheResult<T> load = cacheCore.load(getMD5MessageDigest(key), type);
                if (!flowableEmitter.isCancelled()) {
                    if (load != null) {
                        flowableEmitter.onNext(load);
                        flowableEmitter.onComplete();
                    } else {
                        flowableEmitter.onError(new NullPointerException("Not find the key corresponding to the cache"));
                    }
                }
            }
        }, backpressureStrategy);
    }


    public <T> Observable<Boolean> save(final String key, final T value) {
        return save(key, value, CacheTarget.MemoryAndDisk);
    }

    /**
     * 保存
     */
    public <T> Observable<Boolean> save(final String key, final T value, final CacheTarget target) {
        return Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> observableEmitter) throws Exception {
                boolean save = cacheCore.save(getMD5MessageDigest(key), value, target);
                if (!observableEmitter.isDisposed()) {
                    observableEmitter.onNext(save);
                    observableEmitter.onComplete();
                }
            }
        });
    }

    /**
     * 保存
     */
    public <T> Flowable<Boolean> save2Flowable(final String key, final T value, final CacheTarget target) {
        return save2Flowable(key, value, target, BackpressureStrategy.LATEST);
    }

    /**
     * 保存
     */
    public <T> Flowable<Boolean> save2Flowable(final String key, final T value, final CacheTarget target, BackpressureStrategy strategy) {
        return Flowable.create(new FlowableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(FlowableEmitter<Boolean> flowableEmitter) throws Exception {
                boolean save = cacheCore.save(getMD5MessageDigest(key), value, target);
                if (!flowableEmitter.isCancelled()) {
                    flowableEmitter.onNext(save);
                    flowableEmitter.onComplete();
                }
            }
        }, strategy);
    }

    /**
     * 是否包含
     *
     * @param key
     * @return
     */
    public boolean containsKey(final String key) {
        return cacheCore.containsKey(getMD5MessageDigest(key));
    }

    /**
     * 删除缓存
     */
    public boolean remove(final String key) {
        return cacheCore.remove(getMD5MessageDigest(key));
    }

    /**
     * 清空缓存
     */
    public Observable<Boolean> clear() {
        return Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> observableEmitter) throws Exception {
                try {
                    cacheCore.clear();
                    if (!observableEmitter.isDisposed()) {
                        observableEmitter.onNext(true);
                        observableEmitter.onComplete();
                    }
                } catch (IOException e) {
                    RxCacheLogUtils.log(e);
                    if (!observableEmitter.isDisposed()) {
                        observableEmitter.onError(e);
                    }
                }
            }
        });
    }

    /**
     * 清空缓存
     */
    public void clear2() throws IOException {
        cacheCore.clear();
    }


    /**
     * 构造器
     */
    public static final class Builder {
        private static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
        private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
        private static final int DEFAULT_MEMORY_CACHE_SIZE = (int) (Runtime.getRuntime().maxMemory() / 8);//运行内存的8分之1
        private Integer memoryMaxSize;
        private Long diskMaxSize;
        private int appVersion;
        private File diskDir;
        private IDiskConverter diskConverter;

        public Builder() {
        }

        /**
         * 不设置,默认为运行内存的8分之1.设置0,或小于0,则不开启内存缓存;
         */
        public Builder memoryMax(int maxSize) {
            this.memoryMaxSize = maxSize;
            return this;
        }

        /**
         * 不设置,默认为1.需要注意的是,每当版本号改变,缓存路径下存储的所有数据都会被清除掉,所有的数据都应该从网上重新获取.
         */
        public Builder appVersion(int appVersion) {
            this.appVersion = appVersion;
            return this;
        }

        public Builder diskDir(File directory) {
            this.diskDir = directory;
            return this;
        }


        public Builder diskConverter(IDiskConverter converter) {
            this.diskConverter = converter;
            return this;
        }

        /**
         * 不设置, 默为认50MB.设置0,或小于0,则不开启硬盘缓存;
         */
        public Builder diskMax(long maxSize) {
            this.diskMaxSize = maxSize;
            return this;
        }

        public Builder setDebug(boolean debug) {
            RxCacheLogUtils.DEBUG = debug;
            return this;
        }

        public RxCache build() {
            if (this.diskDir == null) {
                throw new NullPointerException("DiskDir can not be null.");
            }
            if (!diskDir.exists() && !diskDir.mkdirs()) {
                throw new RuntimeException("can't make dirs in " + diskDir.getAbsolutePath());
            }
            if (this.diskConverter == null) {
                this.diskConverter = new SerializableDiskConverter();
            }
            if (memoryMaxSize == null) {
                memoryMaxSize = DEFAULT_MEMORY_CACHE_SIZE;
            }
            if (diskMaxSize == null) {
                diskMaxSize = calculateDiskCacheSize(diskDir);
            }
            appVersion = Math.max(1, this.appVersion);
            return new RxCache(this);
        }

        private static long calculateDiskCacheSize(File dir) {
            long size = 0;

            try {
                StatFs statFs = new StatFs(dir.getAbsolutePath());
                long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize();
                // Target 2% of the total space.
                size = available / 50;
            } catch (IllegalArgumentException ignored) {
                RxCacheLogUtils.log(ignored);
            }
            // Bound inside min/max size for disk cache.
            return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE);
        }

    }

    static String getMD5MessageDigest(String buffer) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer.getBytes());
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            RxCacheLogUtils.log(e);
            return buffer;
        }
    }

}