mirror of https://github.com/halo-dev/halo
Enhance string cache store
parent
98a6fc9e75
commit
b0cb31ad48
|
@ -1,6 +1,15 @@
|
||||||
package run.halo.app.cache;
|
package run.halo.app.cache;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.lang.NonNull;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import run.halo.app.exception.ServiceException;
|
||||||
|
import run.halo.app.utils.JsonUtils;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* String cache store.
|
* String cache store.
|
||||||
|
@ -10,4 +19,32 @@ import lombok.extern.slf4j.Slf4j;
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public abstract class StringCacheStore extends AbstractCacheStore<String, String> {
|
public abstract class StringCacheStore extends AbstractCacheStore<String, String> {
|
||||||
|
|
||||||
|
public <T> void putAny(String key, T value) {
|
||||||
|
try {
|
||||||
|
put(key, JsonUtils.objectToJson(value));
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new ServiceException("Failed to convert " + value + " to json", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> void putAny(@NonNull String key, @NonNull T value, long timeout, @NonNull TimeUnit timeUnit) {
|
||||||
|
try {
|
||||||
|
put(key, JsonUtils.objectToJson(value), timeout, timeUnit);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new ServiceException("Failed to convert " + value + " to json", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> Optional<T> getAny(String key, Class<T> type) {
|
||||||
|
Assert.notNull(type, "Type must not be null");
|
||||||
|
|
||||||
|
return get(key).map(value -> {
|
||||||
|
try {
|
||||||
|
return JsonUtils.jsonToObject(value, type);
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Failed to convert json to type: " + type.getName(), e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,27 @@
|
||||||
|
package run.halo.app.utils;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author johnniang
|
||||||
|
* @date 19-4-29
|
||||||
|
*/
|
||||||
|
public class JsonUtilsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void longConvertTest() throws IOException {
|
||||||
|
long num = 10;
|
||||||
|
|
||||||
|
String result = JsonUtils.objectToJson(num);
|
||||||
|
|
||||||
|
assertEquals("10", result);
|
||||||
|
|
||||||
|
num = JsonUtils.jsonToObject("10", Long.class);
|
||||||
|
|
||||||
|
assertEquals(10, num);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue