org.babyfish.jimmer.sql.cache.spi.AbstractRemoteHashBinder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jimmer-sql Show documentation
Show all versions of jimmer-sql Show documentation
A revolutionary ORM framework for both java and kotlin
package org.babyfish.jimmer.sql.cache.spi;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.babyfish.jimmer.meta.ImmutableProp;
import org.babyfish.jimmer.meta.ImmutableType;
import org.babyfish.jimmer.sql.cache.CacheTracker;
import org.babyfish.jimmer.sql.cache.SerializationException;
import org.babyfish.jimmer.sql.cache.chain.LockableBinder;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.StringWriter;
import java.time.Duration;
import java.util.*;
public abstract class AbstractRemoteHashBinder
extends AbstractRemoteBinder
implements LockableBinder.Parameterized {
protected AbstractRemoteHashBinder(
@Nullable ImmutableType type,
@Nullable ImmutableProp prop,
@Nullable CacheTracker tracker,
@Nullable ObjectMapper objectMapper,
Duration duration,
int randomPercent
) {
super(type, prop, tracker, objectMapper, duration, randomPercent);
}
@Override
public final Map getAll(Collection keys) {
return getAll(keys, Collections.emptySortedMap());
}
@Override
public final void setAll(Map map) {
setAll(map, Collections.emptySortedMap());
}
@Override
public final Map getAll(Collection keys, SortedMap parameterMap) {
Collection redisKeys = serializedKeys(keys);
String hashKey = hashKey(parameterMap);
List values = read(redisKeys, hashKey);
return valueSerializer.deserialize(keys, values);
}
@Override
public final void setAll(Map map, SortedMap parameterMap) {
Map convertedMap = valueSerializer.serialize(map, this::serializedKey);
String hashKey = hashKey(parameterMap);
write(convertedMap, hashKey);
}
protected abstract List read(Collection keys, String hashKey);
protected abstract void write(Map map, String hashKey);
private String hashKey(SortedMap parameterMap) {
try {
StringWriter writer = new StringWriter();
try {
writer.write("{");
boolean addComma = false;
for (Map.Entry e : parameterMap.entrySet()) {
if (addComma) {
writer.write(",");
} else {
addComma = true;
}
writer.write("\"");
writer.write(e.getKey());
writer.write("\":");
writer.write(objectMapper.writeValueAsString(e.getValue()));
}
writer.write("}");
writer.flush();
return writer.toString();
} finally {
writer.close();
}
} catch (IOException ex) {
throw new SerializationException(ex);
}
}
}