Retrofit 風格的 RxCache及其多種緩存替換算法

田園風光.jpg

RxCache 是一個支持 Java 和 Android 的 Local Cache 。

之前的文章《給 Java 和 Android 構建一個簡單的響應式Local Cache》《RxCache 整合 Android 的持久層框架 greenDAO、Room》曾詳細介紹過它。

目前,對框架增加一些 Annotation 以及 Cache 替換算法。

一. 基于 Annotation 完成緩存操作

類似 Retrofit 風格的方式,支持通過標注 Annotation 來完成緩存的操作。

例如先定義一個接口,用于定義緩存的各種操作。

public interface Provider {

    @CacheKey("user")
    @CacheMethod(methodType = MethodType.GET)
    <T> Record<T> getData(@CacheClass Class<T> clazz);


    @CacheKey("user")
    @CacheMethod(methodType = MethodType.SAVE)
    @CacheLifecycle(duration = 2000)
    void putData(@CacheValue User user);


    @CacheKey("user")
    @CacheMethod(methodType = MethodType.REMOVE)
    void removeUser();

    @CacheKey("test")
    @CacheMethod(methodType = MethodType.GET, observableType = ObservableType.MAYBE)
    <T> Maybe<Record<T>> getMaybe(@CacheClass Class<T> clazz);
}

通過 CacheProvider 創建該接口,然后可以完成各種緩存操作。

public class TestCacheProvider {

    public static void main(String[] args) {


        RxCache.config(new RxCache.Builder());

        RxCache rxCache = RxCache.getRxCache();

        CacheProvider cacheProvider = new CacheProvider.Builder().rxCache(rxCache).build();

        Provider provider = cacheProvider.create(Provider.class);

        User u = new User();
        u.name = "tony";
        u.password = "123456";

        provider.putData(u); // 將u存入緩存中

        Record<User> record = provider.getData(User.class); // 從緩存中獲取key="user"的數據

        if (record!=null) {

            System.out.println(record.getData().name);
        }

        provider.removeUser(); // 從緩存中刪除key="user"的數據

        record = provider.getData(User.class);

        if (record==null) {

            System.out.println("record is null");
        }

        User u2 = new User();
        u2.name = "tony2";
        u2.password = "000000";
        rxCache.save("test",u2);

        Maybe<Record<User>> maybe = provider.getMaybe(User.class); // 從緩存中獲取key="test"的數據,返回的類型為Maybe
        maybe.subscribe(new Consumer<Record<User>>() {
            @Override
            public void accept(Record<User> userRecord) throws Exception {

                User user = userRecord.getData();
                if (user!=null) {

                    System.out.println(user.name);
                    System.out.println(user.password);
                }
            }
        });
    }
}

CacheProvider 核心是 create(),它通過動態代理來創建Provider。

    public <T> T create(Class<T> clazz) {

        CacheProxy cacheProxy = new CacheProxy(rxCache);

        try {
            return (T) Proxy.newProxyInstance(CacheProvider.class.getClassLoader(), new Class[]{clazz}, cacheProxy);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

其中,CacheProxy 實現了 InvocationHandler 接口,是創建代理類的調用處理器。

package com.safframework.rxcache.proxy;

import com.safframework.rxcache.RxCache;
import com.safframework.rxcache.proxy.annotation.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Created by tony on 2018/10/30.
 */
public class CacheProxy implements InvocationHandler {

    RxCache rxCache;

    public CacheProxy(RxCache rxCache) {

        this.rxCache = rxCache;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        CacheMethod cacheMethod = method.getAnnotation(CacheMethod.class);
        CacheKey cacheKey = method.getAnnotation(CacheKey.class);
        CacheLifecycle cacheLifecycle = method.getAnnotation(CacheLifecycle.class);

        Annotation[][] allParamsAnnotations = method.getParameterAnnotations();

        Class cacheClazz = null;
        Object cacheValue = null;

        if (allParamsAnnotations != null) {
            for (int i = 0; i < allParamsAnnotations.length; i++) {
                Annotation[] paramAnnotations = allParamsAnnotations[i];
                if (paramAnnotations != null) {
                    for (Annotation annotation : paramAnnotations) {
                        if (annotation instanceof CacheClass) {
                            cacheClazz = (Class) args[i];
                        }

                        if (annotation instanceof CacheValue) {
                            cacheValue = args[i];
                        }
                    }
                }
            }
        }

        if (cacheMethod!=null) {

            MethodType methodType = cacheMethod.methodType();

            long duration = -1;

            if (cacheLifecycle != null) {
                duration = cacheLifecycle.duration();
            }

            if (methodType == MethodType.GET) {

                ObservableType observableType = cacheMethod.observableType();

                if (observableType==ObservableType.NOUSE) {

                    return  rxCache.get(cacheKey.value(),cacheClazz);
                } else if (observableType == ObservableType.OBSERVABLE){

                    return  rxCache.load2Observable(cacheKey.value(),cacheClazz);
                } else if (observableType==ObservableType.FLOWABLE) {

                    return  rxCache.load2Flowable(cacheKey.value(),cacheClazz);
                } else if (observableType==ObservableType.SINGLE) {

                    return  rxCache.load2Single(cacheKey.value(),cacheClazz);
                } else if (observableType==ObservableType.MAYBE) {

                    return  rxCache.load2Maybe(cacheKey.value(),cacheClazz);
                }

            } else if (methodType == MethodType.SAVE) {

                rxCache.save(cacheKey.value(),cacheValue,duration);

            } else if (methodType == MethodType.REMOVE) {

                rxCache.remove(cacheKey.value());
            }
        }

        return null;
    }
}

CacheProxy 的 invoke() 方法先獲取 Method 所使用的 Annotation,包括CacheMethod、CacheKey、CacheLifecycle。

其中,CacheMethod 是最核心的 Annotation,它取決于 rxCache 使用哪個方法。CacheMethod 支持的方法類型包括:獲取、保存、刪除緩存。當 CacheMethod 的 methodType 是 GET 類型,則可能會返回 RxJava 的各種 Observable 類型,或者還是返回所存儲的對象類型。

CacheKey 是任何方法都需要使用的 Annotation。CacheLifecycle 只有保存緩存時才會使用。

二. 支持多種緩存替換算法

RxCache 包含了兩級緩存: Memory 和 Persistence 。

Memory 的默認實現 FIFOMemoryImpl、LRUMemoryImpl、LFUMemoryImpl 分別使用 FIFO、LRU、LFU 算法來緩存數據。

2.1 FIFO

通過使用 LinkedList 存放緩存的 keys,ConcurrentHashMap 存放緩存的數據,就可以實現 FIFO。

2.2 LRU

LRU是Least Recently Used的縮寫,即最近最少使用,常用于頁面置換算法,是為虛擬頁式存儲管理服務的。

使用 ConcurrentHashMap 和 ConcurrentLinkedQueue 實現該算法。如果某個數據已經存放在緩存中,則從 queue 中刪除并添加到 queue 的第一個位置。如果緩存已滿,則從 queue 中刪除最后面的數據。并把新的數據添加到緩存。

public class LRUCache<K,V> {

    private Map<K,V> cache = null;
    private AbstractQueue<K> queue = null;
    private int size = 0;

    public LRUCache() {

        this(Constant.DEFAULT_CACHE_SIZE);
    }

    public LRUCache(int size) {

        this.size = size;
        cache = new ConcurrentHashMap<K,V>(size);
        queue = new ConcurrentLinkedQueue<K>();
    }

    public boolean containsKey(K key) {

        return cache.containsKey(key);
    }

    public V get(K key) {

        //Recently accessed, hence move it to the tail
        queue.remove(key);
        queue.add(key);
        return cache.get(key);
    }

    public V getSilent(K key) {

        return cache.get(key);
    }

    public void put(K key, V value) {

        //ConcurrentHashMap doesn't allow null key or values
        if(key == null || value == null) throw new RxCacheException("key is null or value is null");

        if(cache.containsKey(key)) {
            queue.remove(key);
        }

        if(queue.size() >= size) {
            K lruKey = queue.poll();
            if(lruKey != null) {
                cache.remove(lruKey);
            }
        }

        queue.add(key);
        cache.put(key,value);
    }

    /**
     * 獲取最近最少使用的值
     * @return
     */
    public V getLeastRecentlyUsed() {

        K remove = queue.remove();
        queue.add(remove);
        return cache.get(remove);
    }

    public void remove(K key) {

        cache.remove(key);
        queue.remove(key);
    }

    public void clear() {

        cache.clear();
        queue.clear();
    }
    ......
}

2.3 LFU

LFU是Least Frequently Used的縮寫,即最近最不常用使用。

看上去跟 LRU 類似,其實它們并不相同。LRU 是淘汰最長時間未被使用的數據,而 LFU 是淘汰一定時期內被訪問次數最少的數據。

LFU 會記錄數據在一定時間內的使用次數。稍顯復雜感興趣的可以閱讀 RxCache 中相關的源碼。

三. 總結

RxCache 大體已經完成,初步可以使用。

RxCache github 地址:https://github.com/fengzhizi715/RxCache
Android 版本的 RxCache github 地址:https://github.com/fengzhizi715/RxCache4a

對于 Android ,除了支持常見的持久層框架之外,還支持 RxCache 轉換成 LiveData。如果想要跟 Retrofit 結合,可以通過 RxCache 的 transform 策略。

對于Java 后端,RxCache 只是一個本地緩存,不適合存放大型的數據。但是其內置的 Memory 層包含了多種緩存替換算法,不用內置的 Memory 還可以使用 Guava Cache、Caffeine 。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1我們都聽過 cache,當你問他們是什么是緩存的時候,他們會給你一個完美的答案,可是他們不知道緩存是怎么構建的,...
    織田信長閱讀 1,519評論 1 20
  • 緩存是最直接有效提升系統性能的手段之一。個人認為用好用對緩存是優秀程序員的必備基本素質。 本文結合實際開發經驗,從...
    Java小生閱讀 829評論 1 3
  • 理論總結 它要解決什么樣的問題? 數據的訪問、存取、計算太慢、太不穩定、太消耗資源,同時,這樣的操作存在重復性。因...
    jiangmo閱讀 2,903評論 0 11
  • 前言 主題是Mybatis一級和二級緩存的應用及源碼分析。希望在本場chat結束后,能夠幫助讀者朋友明白以下三點。...
    余平的余_余平的平閱讀 1,349評論 0 12
  • 當夏日的傍晚溫暖的風徐徐吹來,夾雜著泥土與花的芬芳,我在回想一天的時光。當我抬頭看法國梧桐時,輕輕的瞥一眼天空,灰...
    簟紋燈影閱讀 312評論 0 0