RoboSpice - 未获取缓存数据

RoboSpice - Not getting Cache Data

我正在使用 RoboSpice 进行网络服务调用,如下所示。

spiceManager.execute(request, lastRequestCacheKey,
                DurationInMillis.ONE_DAY, this);

Bu 每次都使用 loadDataFromNetwork() 进行网络请求。

似乎缓存数据是empty.Got这条消息"Cache content not available or expired or disabled"

我做错了什么?

已解决。对于正在寻找相同内容的人,请阅读。


  • RoboSpice starter guides 开始,应该为每个 Web 服务请求创建自定义请求(SpringAndroidSpiceRequest;基于模型对象)。
  • 但是我有很多 Web 服务请求和不同的模型 类。所以,如果我们为每个模型创建单独的请求,代码结构将变得混乱.
  • 所以,创建了一个通用请求
  • 但是,我无法从缓存中获取数据。所以只需重写getResultType()

    @Override
    public Class<Object> getResultType() {
        return (Class<Object>) clazz;
    }
    

这是完整的代码。

public class WebServiceRequest extends SpringAndroidSpiceRequest<Object> {

private String url;
private int TIMEOUT_TIME = 15000;
Class<?> clazz;
HTTPMethod httpMethod;
private MultiValueMap multiValueMap;

public WebServiceRequest(HTTPMethod httpMethod, String Token, String url, Class<?> clazz, @Nullable MultiValueMap multiValueMap) {
    super(Object.class);
    this.httpMethod = httpMethod;
    this.token = Token;
    this.url = url;
    this.clazz = clazz;
    this.multiValueMap = multiValueMap;
}

@Override
public Object loadDataFromNetwork() {
    Object response = null;
    try {
        if (this.httpMethod == HTTPMethod.GET) {
            Uri.Builder uriBuilder = Uri.parse(this.url).buildUpon();
            String urls = uriBuilder.build().toString();
            response = getRestTemplate().getForObject(urls, clazz);
        } else {
            RestTemplate restTemplate = new RestTemplate(true);
            restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
            restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<?> requestEntity = new HttpEntity<Object>(this.multiValueMap, requestHeaders);
            // Test URL : http://posttestserver.com/post.php  
            response = restTemplate.postForObject(this.url, requestEntity, clazz);
        }
        manageTimeOuts(getRestTemplate());
        return response;
    } catch (Exception timeoutException) {
        return response;
    }

}

@Override
public Class<Object> getResultType() {
    return (Class<Object>) clazz;
}

private void manageTimeOuts(RestTemplate restTemplate) {
    // set timeout for requests
    ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
    if (factory instanceof HttpComponentsClientHttpRequestFactory) {
        HttpComponentsClientHttpRequestFactory advancedFactory = (HttpComponentsClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(TIMEOUT_TIME);
        advancedFactory.setReadTimeout(TIMEOUT_TIME);
    } else if (factory instanceof SimpleClientHttpRequestFactory) {
        SimpleClientHttpRequestFactory advancedFactory = (SimpleClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(TIMEOUT_TIME);
        advancedFactory.setReadTimeout(TIMEOUT_TIME);
    }
}

public String createCacheKey() {
    return clazz.getName() + token;
}

}

启动 Web 服务请求并获取响应回调,如下所示。

public class HomeActivity extends AppCompatActivity implements RequestListener<Object> {

    private SpiceManager spiceManager = new SpiceManager(
            JacksonSpringAndroidSpiceService.class);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        String url = "http://192.168.56.1:8080/JSONRestWebServiceExample/JavaCodeGeeks/AuthorService/authors";
        WebServiceRequest request = new WebServiceRequest(HTTPMethod.GET, null, url, new ArrayList<Model>().getClass(), null);    
        String lastRequestCacheKey = request.createCacheKey();
        spiceManager.execute(request, lastRequestCacheKey,
                DurationInMillis.ONE_DAY, this);
    }

    @Override
    protected void onStart() {
        spiceManager.start(this);
        super.onStart();
    }

    @Override
    protected void onStop() {
        spiceManager.shouldStop();
        super.onStop();
    }

    @Override
    public void onRequestSuccess(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<Model> metricsResponse = objectMapper.convertValue(object, new TypeReference<List<Model>>() {
        });

        if (object == null) {
            onRequestFailure(new SpiceException("Something went wrong"));
            return;
        }
    }

    @Override
    public void onRequestFailure(SpiceException spiceException) {
        Snackbar.make(getWindow().getDecorView().getRootView(), spiceException.getMessage(), Snackbar.LENGTH_SHORT)
                .setAction("Action", null).show();
    }
}