私は、Web サービス要求の負荷が高い Android のアプリケーションに取り組んでいます。
ユーザーがユーザー名とパスワードを導入し、サーバーが結果とトークンで応答する LoginActivity を既に持っています。次に、いくつかのアクティビティ (すべて共通の BaseActivity から拡張されます) が重い要求を実行します。
また、すべてのサービス要求と HTTP 請願を担当する ServiceManager クラスもあります。
この正味負荷を軽減するために HttpResponseCache の実装に取り組んでいます。現在、次のコードがあります。
私のLoginActivityの(最初に起動された)onCreateで:
//HTTP cache
try {
File httpCacheDir = new File(this.getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; //10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
Log.d(TAG, "Cache installed");
} catch (IOException e) {
Log.i(TAG, "HTTP response cache installation failed:" + e);
}
ServiceManager の httpRequest 関数では、HTTP 要求を作成しようとするたびに実際に実行されます。
//HTTPS connection
URL requestedUrl = new URL(uri);
httpsConnection = (HttpURLConnection) requestedUrl.openConnection();
httpsConnection.setUseCaches(true);
httpsConnection.setDefaultUseCaches(true);
httpsConnection.setRequestMethod("GET");
BufferedReader br = new BufferedReader(
new InputStreamReader(httpsConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
httpResponse += line;
}
br.close();
httpsConnection.disconnect();
HttpResponseCache cache = HttpResponseCache.getInstalled();
Log.d(TAG, "Cache: " + cache);
if (cache != null) {
Log.d(TAG, "Net count: " + cache.getNetworkCount());
Log.d(TAG, "Hit count: " + cache.getHitCount());
Log.d(TAG, "Request count: " + cache.getRequestCount());
cache.flush();
}
try{
URI uriCached = new URI("<myurl>");
CacheResponse cr = cache.get(uriCached, "GET", null);
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(cr.getBody()));
while ((line = br.readLine()) != null) {
Log.d(TAG, line);
}
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
現在、サーバー側の準備が整っていないため、リクエストを送信する URL は常に同じです。
ご覧のとおり、いくつかのことをデバッグしています。結果は次のとおりです。
- キャッシュがインストールされています
- キャッシュ: android.net.http.HttpResponseCache@b3e3b6
- ネットカウント: X
- ヒット数: 0
- リクエスト数: X
- {myJson}
ご覧のとおり、キャッシュは cache.get() メソッドで取得した JSON を読み取ることができますが、ヒットすることはありません。
応答のヘッダーにあるサーバー側のディレクティブ Cache-Control は次のとおりです: Cache-Control:public Cache-Control:max-age=3800
キャッシュがヒットしないのはなぜですか?
どうもありがとうございました!