有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想将netsted HashMap存储在Redis中,并使用单个键

例如:

HashMap<String, HashMap<String,String>> map = new  HashMap<>();

请建议:

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

共 (1) 个答案

  1. # 1 楼答案

    REDIS现在允许嵌套HashMap https://redis.io/topics/data-types

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>1.5.22.RELEASE</version>
    </dependency>
    
    public class Redis {
    
        @Autowired
        RedisService redisService;
    
        @Cacheable(value = "name", key = "keyvalue")
        public Map<String, HashMap<String, String>> redisNestedMap(String keyvalue) {
            return redisService.getNestedMap();
        }
    
    }
    
    @Component
    public class RedisService {
    
        public Map<String, HashMap<String, String>> getNestedMap() {
            Map<String, HashMap<String, String>> nestedMap = new HashMap<>();
            HashMap<String, String> value = new HashMap<>();
            value.put("key", "value");
            nestedMap.put("one", value);
            return nestedMap;
        }
    
    }