From b0cb31ad48acd16b76001cf6ebb2663a3b1cd6a2 Mon Sep 17 00:00:00 2001 From: johnniang Date: Mon, 29 Apr 2019 01:24:02 +0800 Subject: [PATCH] Enhance string cache store --- .../run/halo/app/cache/StringCacheStore.java | 37 +++++++++++++++++++ .../run/halo/app/utils/JsonUtilsTest.java | 27 ++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/test/java/run/halo/app/utils/JsonUtilsTest.java diff --git a/src/main/java/run/halo/app/cache/StringCacheStore.java b/src/main/java/run/halo/app/cache/StringCacheStore.java index 69d49c46..f683ceb2 100644 --- a/src/main/java/run/halo/app/cache/StringCacheStore.java +++ b/src/main/java/run/halo/app/cache/StringCacheStore.java @@ -1,6 +1,15 @@ 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 { + public 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 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 Optional getAny(String key, Class 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; + } + }); + } } diff --git a/src/test/java/run/halo/app/utils/JsonUtilsTest.java b/src/test/java/run/halo/app/utils/JsonUtilsTest.java new file mode 100644 index 00000000..6612de52 --- /dev/null +++ b/src/test/java/run/halo/app/utils/JsonUtilsTest.java @@ -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); + } +} \ No newline at end of file -- GitLab