提交 b0cb31ad 编写于 作者: J johnniang

Enhance string cache store

上级 98a6fc9e
package run.halo.app.cache;
import com.fasterxml.jackson.core.JsonProcessingException;
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.
......@@ -10,4 +19,32 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
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;
}
});
}
}
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);
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册