2017-06-15 559 views
0

我正在尝试使用Lettuce的同步命令来执行HSCAN。问题是我无法弄清楚初始化MapScanCursor的正确方法。我对构造函数没有成功,并且MapScanCursor.INITIAL给出了类型ScanCursor(没有运气把它变成MapScanCursor)。如何初始化Lettuce Redis客户端库中的MapScanCursor?

下面是一个例子:

RedisClient redisClient = RedisClient.create("redis://" + url + ":" + port); 
RedisHashCommands<String, String> redisCommands = redisClient.connect().sync(); 
List<String> fields = new LinkedList<>(); 

MapScanCursor<String, String> scanCursor = ? 

do { 
    scanCursor = redisCommands.hscan(key, scanCursor); 
    fields.addAll(scanCursor.getMap().keySet()); 
} while (!scanCursor.isFinished()); 

我应该如何初始化 “scanCursor”?

回答

0

你有两个选择:

要回答你的问题,只有hscan(key)初始化scanCursor

MapScanCursor<String, String> scanCursor = null; 

do { 
    if (scanCursor == null) { 
     scanCursor = redisCommands.hscan(key); 
    } else { 
     scanCursor = redisCommands.hscan(key, scanCursor); 
    } 
    fields.addAll(scanCursor.getMap().keySet()); 
} while (!scanCursor.isFinished()); 

或者,你可以使用ScanIterator(见生菜4.4),这是一个Iterator,涵盖Redis的SCAN使用的复杂性:更新了do…while基于

ScanIterator<KeyValue<String, String>> iterator = ScanIterator.hscan(redisCommands, key); 

while (iterator.hasNext()) { 

    KeyValue<String, String> next = iterator.next(); 
    // … 
} 

更新

根据tffritchman的评论的方法。

+0

非常感谢您提供了一个很好的选择。这解决了我的问题。但是,一个小问题是,当使用第一个选项时,必须在再次调用'hscan'之前检查'!scanCursor.isFinished()'。否则,如果在第一次通话中扫描结束,您将收到错误。例如。 'scanCursor = redisCommands.hscan(key); while(!scanCursor.isFinished()){scanCursor = redisCommands.hscan(key,scanCursor); fields.addAll(scanCursor.getMap()的keySet()); }' – tcfritchman

相关问题