【问题标题】:getting the entire data in redis from redisTemplate从 redisTemplate 获取 redis 中的全部数据
【发布时间】:2016-02-28 02:55:39
【问题描述】:

我对 redis 比较陌生。 我正在设计一个rest API,以获取redis db中的整个数据集。

我使用下面的代码来获取所有的键

公共地图 getAllRedisData() {

    Map<Object, Object> map  = new HashMap<>();
    Set<byte[]> keys = redisService.getTemplate().getConnectionFactory().getConnection().keys("*".getBytes());
    Iterator<byte[]> it = keys.iterator();

    while(it.hasNext()){
        byte[] data = (byte[])it.next();
       // String key = new String(data,0,data.length);
        Object key = null;
        try {
            key = getObjectFromByteArray(data);
            System.out.println(key);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }    
    return map;
}

private Object getObjectFromByteArray(byte[] bytes) throws IOException, ClassNotFoundException
{
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
         ObjectInput in = new ObjectInputStream(bis)) {
        return in.readObject();
    } 
}

我能够获取所有键,但无法检索所有键的值。下面是方法 "对象值 = redisService.getTemplate().opsForValue().get("");"

我猜这是因为某些键的数据类型不同。

如果我必须修改/改变我的方法,请告诉我。

【问题讨论】:

    标签: java spring-mvc redis


    【解决方案1】:

    第一个 keys 不应在生产中使用。相反,您可以使用 scan 命令。

    当你有 key 后,你可以调用 redis type 命令来检索对象的 DataType。

    DataType -> NONE, STRING, LIST, SET, ZSET, HASH
    

    然后就可以调用正确的函数来获取数据了

    在大型数据集上,这可能需要一段时间。你确定你的rest api需要把所有数据都放到redis中吗?您可以使用带有扫描的模式来仅检索您真正需要的数据。

    【讨论】:

      【解决方案2】:

      我没有测试,但试试这个

          try {
              Object value = getObjectFromByteArray(redisService.getTemplate().getConnectionFactory().getConnection().get(data));
              key = getObjectFromByteArray(data);
              System.out.println(key);
          } catch (ClassNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      

      【讨论】:

        猜你喜欢
        • 2017-06-17
        • 2015-10-15
        • 2015-08-07
        • 2020-04-19
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 2020-07-05
        相关资源
        最近更新 更多