単純に、タイムスタンプ、メッセージIDなどのフィールドが考慮されるべきではないので、キャッシュが正しいキーを選択する方法を変更する必要がありますキーを取得する。 キーオブジェクトの実際のハッシュ関数は、自分のコードですでに認識されているため、変更できません。
Guavaキャッシュでは可能ですか?そして回避策はありますか?
これは私の設定です:キーを挿入するときのカスタム等価/ハッシュ
CacheBuilder.newBuilder().maximumSize(CACHE_SIZE).recordStats().
expireAfterWrite(DEFAULT_AGE, TimeUnit.DAYS).build(
new CacheLoader<Request, Response>() {
@Override
public Response load(Request request) {
return request.getResponse();
}
});
そしてこれが(私のコードのどこかで使用)私のハッシュ関数である:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + code;
result = prime * result + messageID; // <= **this one shouldn't evaluated**
result = prime * result + Arrays.hashCode(payload);
result = prime * result + (int) (timestamp^timestamp >>> 32); // <= **this one shouldn't evaluated**
result = prime * result + (type == null ? 0 : type.hashCode());
result = prime * result + version;
return result;
}
はところで、独自の実装を使用してキャッシュのこの種でありますハッシュ関数(例えば、イントロスペクションを通じて)、またはデフォルトのものを使用していますか?
** EDIT: **
としては、回答に指摘し、この結果を達成するための最良の方法は、ラッパークラスです。
私のソリューション:
/**
* Nested class to store a request as a key in the cache. It is needed to
* normalize the variable fields of the normal requests.
*/
private static final class CachedRequest extends Request {
private static CachedRequest fromRequest(Request request) {
// set only the fields that cannot change between two same requests
// ...
}
@Override
public int hashCode() {
HashFunction hashFunction = Hashing.md5();
HashCode hashCode;
// ...
return hashCode.asInt();
}
@Override
public boolean equals(Object obj) {
// coherent with hashCode()
// ...
}
}
私はそれが独自のハッシュ実装を使用した場合、非常に有用なユーティリティであるとは思いません。 – jtahlborn
また、「実際の」オブジェクトを認識するためにすでに使用されているため、私はhash()関数を変更できません。 – jtahlborn
実際に私はこの機能を追加するつもりはありませんが、誰かがこのような状況に対処する方法を知っていれば。 – Hamal000