如何在Redis中存储嵌套的Hashmap?

Min*_*nal 6 java hashmap redis

我想将 netsted 存储HashMapRedis单个密钥中。

例如 :

HashMap<String, HashMap<String,String>> map = new  HashMap<>();
Run Code Online (Sandbox Code Playgroud)

请建议:

  • 有没有办法存储上述数据结构?
  • 我们怎样才能做到这一点?

Dar*_*tel 4

Redis 目前还不支持。然而,除了 之外,还有一种方法可以做到这一点rejson

您可以将其转换为 JSON 并存储在 Redis 中并检索。遵循我在 Jackson 中使用的实用方法。

将对象转换为字符串:

public static String stringify(Object object) {
    ObjectMapper jackson = new ObjectMapper();
    jackson.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    try {
        return jackson.writeValueAsString(object);
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "Error while creating json: ", ex);
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

例子 :stringify(obj);

将字符串转换为对象:

public static <T> T objectify(String content, TypeReference valueType) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
        dateFormat.setTimeZone(Calendar.getInstance().getTimeZone());
        mapper.setDateFormat(dateFormat);
        return mapper.readValue(content, valueType);
    } catch (Exception e) {
        LOG.log(Level.WARNING, "returning null because of error : {0}", e.getMessage());
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

例子 :List<Object> list = objectify("Your Json", new TypeReference<List<Object>>(){})

您可以根据您的要求更新此方法。我确信,你知道如何在Redis中添加和更新。