2017-06-15 560 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

相關問題