如何在Google Cloud Endpoint中缓存响应? [英] How to cache the response in google cloud endpoint?

查看:93
本文介绍了如何在Google Cloud Endpoint中缓存响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个使用Google Cloud端点作为后端的Android应用。因此,我正在从该应用程序发出请求。我想将这些请求的响应缓存在内存以及存储中。

I'm making an android app which uses google cloud endpoints as the backend. So I'm making request from the app. I want to cache the response of these requests in memory as well as storage.

我想在手机上缓存响应,这样我就不必

I want to cache the response on the phone, so that I don't have to make unnecessary repeated network requests.

我在互联网上搜索了一些内置解决方案,但在google提供的api中找不到类似的内容。

I searched the internet for some inbuilt solution but couldn't find anything like that in the api provided by google.

我总共要缓存大约2MB的数据。该数据分布在20个端点请求上。

There's a total of about 2MB data that I want to cache. This data is spread over 20 end point requests.

实现此类缓存的最佳选择是什么?

What are my best options to implement such a cache?

推荐答案

我要回答我自己的问题,以便它可以帮助某人,直到有更干净的解决方案可用为止。

I'm going to answer my own question so that it can help someone until there's a more clean solution available.

I正在使用此库来缓存响应: https://github.com/vincentbrison/android-easy-缓存

I'm using this library for caching responses: https://github.com/vincentbrison/android-easy-cache


  1. GCE结果是 GenericJson 。使用 SerializationUtil

  2. 使用序列化响应此代码创建DualCache库样板。 dualCacheByteArray 用于缓存响应, dualCacheDate 用于跟踪 time_to_live_for_response

  1. GCE result is a GenericJson. Serialize the response using this SerializationUtil
  2. Use this code to create DualCache library boilerplate. dualCacheByteArray for caching the response and dualCacheDate for keeping track of time_to_live_for_response

public static final int APP_CACHE_VERSION = 1;
public static final String CACHE_ID = "cache_id_string";
public static final String CACHE_ID_DATE = "cache_id_date";
public static final int RAM_CACHE_SIZE = 5 * 1024 * 1024; // 5 mb
public static final int DISK_CACHE_SIZE = 15 * 1024 * 1024; //15 mb
public static final int RAM_CACHE_SIZE_DATE = 1 * 1024 * 1024; // 5 mb
public static final int DISK_CACHE_SIZE_DATE = 3 * 1024 * 1024; //15 mb


private DualCache<byte[]> dualCacheByteArray;
private DualCache<Date> dualCacheDate;

public DualCache<byte[]> getDualCacheByteArray() {
if (dualCacheByteArray == null) {
    dualCacheByteArray = new DualCacheBuilder<byte[]>(Constants.CACHE_ID, Constants.APP_CACHE_VERSION, byte[].class)
            .useReferenceInRam(Constants.RAM_CACHE_SIZE, new SizeOf<byte[]>() {
                @Override
                public int sizeOf(byte[] object) {
                    return object.length;
                }
            })
            .useDefaultSerializerInDisk(Constants.DISK_CACHE_SIZE, true);
    }
    return dualCacheByteArray;
}

public DualCache<Date> getDualCacheDate() {
if (dualCache == null) {
    dualCacheDate = new DualCacheBuilder<Date>(Constants.CACHE_ID_DATE, Constants.APP_CACHE_VERSION, Date.class)
            .useReferenceInRam(Constants.RAM_CACHE_SIZE_DATE, new SizeOf<Date>() {
                @Override
                public int sizeOf(Date date) {
                    byte[] b = new byte[0];
                    try {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(baos);
                        oos.writeObject(date);
                        oos.flush();
                        byte[] buf = baos.toByteArray();
                        return buf.length;
                    } catch (IOException e) {
                        Log.e("some prob", "error in calculating date size for caching", e);
                    }
                    return sizeOf(date);
                }
            })
            .useDefaultSerializerInDisk(Constants.DISK_CACHE_SIZE_DATE, true);
    }
    return dualCacheDate;
}


  • 现在使用上面的 DualCache 来缓存您的响应。

    getDualCacheByteArray().put(YOUR_RESPONSE_CACHE_KEY, serializedProduct);
    getDualCacheDate().put(YOUR_RESPONSE_CACHE_KEY, new Date());
    


  • 在使用Google Cloud端点提出新请求之前,您应该检查双缓存是否缓存中已经存在旧的响应

  • Before making a new request using google cloud endpoints, you should check in dual cache if the old response is already present in cache

    public byte[] getCachedGenericJsonByteArray(String key, int cacheExpireTimeInMinutes) {
        Date cachingDate = getDualCacheDate().get(key);
        if(cachingDate!=null) {
            long expirationTime = TimeUnit.MILLISECONDS.convert(cacheExpireTimeInMinutes, TimeUnit.MINUTES);
            long timeElapsedAfterCaching = new Date().getTime() - cachingDate.getTime();
            if (timeElapsedAfterCaching >= expirationTime) {
                //the cached data has expired
                return null;
            } else {
                byte[] cachedGenericJsonByteArray = getDualCacheByteArray().get(key);
                return cachedGenericJsonByteArray;
            }
        } else {
        //result for this key was never cached or is cleared
        return null;
        }
    }
    


  • 如果缓存的字节数组不为空,则使用SerializationUtil对其进行反序列化,并将其用作缓存的响应,否则从Google云端点发出新请求

    if the cached byte array is not null, then deserialize it using SerializationUtil and use it as a cached response, else make a new request from google cloud endpoints

    编辑:Sanket Berde在其他答案中指出,在每种情况下都不一定需要使用序列化工具

    EDIT : Using serialization util may not be necessary in every case as pointed out by Sanket Berde in other answer

    这篇关于如何在Google Cloud Endpoint中缓存响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆