Android 使用磁盘缓存支持改装类库
我正在使用网络呼叫中的库。非常棒。但我缺少缓存支持。我不能在HTTP层上使用缓存(通过缓存头)。目前,我正在用实现自定义缓存,但它太复杂了。使用Android 使用磁盘缓存支持改装类库,android,caching,android-library,retrofit,Android,Caching,Android Library,Retrofit,我正在使用网络呼叫中的库。非常棒。但我缺少缓存支持。我不能在HTTP层上使用缓存(通过缓存头)。目前,我正在用实现自定义缓存,但它太复杂了。使用@Cache(过期一天)anotation扩展当前的改装应该非常棒 我当前的代码如下: public static void getRestaurant(int restaurantId, String token, boolean forceNetwork, final Callback<Restaurant> listener) {
@Cache(过期一天)
anotation扩展当前的改装应该非常棒
我当前的代码如下:
public static void getRestaurant(int restaurantId, String token, boolean forceNetwork, final Callback<Restaurant> listener) {
final String key = "getRestaurant-" + restaurantId + "-" + token;
Restaurant restaurant = (Restaurant) getCacheManager().get(key, Restaurant.class, new TypeToken<Restaurant>() {}.getType());
if (restaurant != null && !forceNetwork) {
Log.d(TAG, "Cache hit: " + key);
// Cache
listener.success(restaurant);
} else {
Log.d(TAG, "Network: " + key);
// Retrofit
getNetwork().getRestaurant(restaurantId, token, new retrofit.Callback<Response>() {
@Override
public void success(Response response, retrofit.client.Response response2) {
getCacheManager().put(key, response.result.restaurant, CacheManager.ExpiryTimes.ONE_HOUR.asSeconds(), true);
listener.success(response.result.restaurant);
}
@Override
public void failure(RetrofitError error) {
listener.failure(error.getLocalizedMessage());
}
});
}
}
publicstaticvoidgetrestaurant(int restaurantId、字符串标记、布尔forceNetwork、最终回调侦听器){
最后一个字符串key=“getRestaurant-”+restaurantId+“-”+令牌;
Restaurant Restaurant=(Restaurant)getCacheManager().get(key,Restaurant.class,new-TypeToken(){}.getType());
if(餐厅!=null&&!forceNetwork){
Log.d(标记“缓存命中:”+键);
//缓存
成功(餐厅);
}否则{
Log.d(标签,“网络:”+键);
//改造
getNetwork().getRestaurant(restaurantId、token、new Reformation.Callback()){
@凌驾
public void成功(响应,改装.client.Response响应2){
getCacheManager().put(key,response.result.restaurant,CacheManager.ExpiryTimes.ONE_HOUR.asSeconds(),true);
成功(回应、结果、餐厅);
}
@凌驾
公共无效失败(错误){
失败(错误.getLocalizedMessage());
}
});
}
}
现在,每个方法都有很多样板代码
或者,您知道有哪种库类似于使用缓存支持进行改装
谢谢 您可以包装底层的
客户端
,并将请求URL用作缓存键
public class CachingClient implements Client {
private final Client delegate;
@Override public Response execute(Request request) {
if (!"GET".equals(request.method())) {
return delegate.execute(request);
}
String url = request.url();
// TODO look up 'url' in your cache.
if (cacheHit) {
return createResponse(cacheResult);
}
// Cache miss! Execute with the real HTTP client.
Response response = delegate.execute(request);
// TODO cache 'response' in your cache with the 'url' key.
return response;
}
}
在改型v2中,我们希望通过拦截器启用此类功能,拦截器不仅可以为您提供请求/响应链的挂钩,还可以查找自定义注释,如
@Cache
,这不应该与响应头一起自动执行吗?(不过,您可能需要将OkHttp与之配合使用,以获得磁盘缓存)请参阅改型2中的RxCache
库!