我为Volley提供了一个适配器,用于使用OKhttp3作为传输,DiskBasedCache
作为缓存实现来处理HTTP请求。
我试图使用.remove(url)
从缓存中删除一个特定的JSON提要请求,但它不起作用。下面是一个示例代码:
在活动中提出请求:
String url = "http://somewebsite.com/feed.json"
VolleyStringRequest stringRequest = new VolleyStringRequest(Method.GET,null, url,responseListener(),errorListener());
RequestQueue queue = CustomVolleyRequestQueue.getInstance(context).getRequestQueue();
queue.add(stringRequest);
完成某些操作后删除缓存:
Cache cache = CustomVolleyRequestQueue.getInstance(context).getRequestQueue().getCache();
Cache.Entry cacheEntry = cache.get(url);
if (cacheEntry != null) {
Log.d("cache", "has_cache");
} else {
Log.d("cache", "no cache");
}
cache.remove(url);
然而,在logCat中,密钥url
返回"无缓存",而cache.remove(url)
产生
DiskBasedCache.remove: Could not delete cache entry for key=http://somewebsite.com/feed.json,
filename=-159673043453434434
有人知道如何使用cache.remove(url)
吗?Volley是否使用url作为缓存项的密钥?我不想使用cache.clear()
,只想删除一个特定的请求缓存。
自定义VolleyRequestQueue:
public class CustomVolleyRequestQueue {
private static CustomVolleyRequestQueue mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;
private CustomVolleyRequestQueue(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleyRequestQueue(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new OkHttpStack());
mRequestQueue = new RequestQueue(cache, network);
// Don't forget to start the volley request queue
mRequestQueue.start();
}
return mRequestQueue;
}
}
更新:我已经创建了一个自定义类,它扩展了DiskBasedCache
,以检查它为缓存使用的键。
public class CustomDiskBasedCache extends DiskBasedCache {
public CustomDiskBasedCache(File rootDirectory, int maxCacheSizeInBytes) {
super(rootDirectory, maxCacheSizeInBytes);
}
@Override
public synchronized void put(String key, Entry entry) {
super.put( key, entry);
Log.d("cache_key",key);
}
}
看起来每个缓存密钥都以0:
为前缀,例如:
0:http://somewebsite.com/feed.json
我不知道为什么要添加它。
关于您看到的的调试消息
无法删除的缓存项。。。
这是因为在DiskBasedCache.java中,remove(字符串键)在删除文件不成功时显示调试消息,内存条目无论如何都会被删除,所以现金会消失,而clear()则只显示任何可用的文件。
实际上,您发现了为什么会出现这种情况,因为您要删除的文件不在那里。
所以你第二个问题是为什么你有这个前缀。这是因为你可能会覆盖
public字符串getCacheKey(){
在您的自定义VolleyStringRequest 中