9.5.2 映射(Map)类型的使用范例

Redisson提供的RMapRMapCacheRLocalCachedMap这三种映射(Map)类型的对象均可以使用这种分布式映射归纳(MapReduce)服务。

以下是在映射(Map)类型的基础上采用映射归纳(MapReduce)来实现字数统计的范例:

  1. Mapper对象将每个映射的值用空格且分开。

    1. public class WordMapper implements RMapper<String, String, String, Integer> {
    2. @Override
    3. public void map(String key, String value, RCollector<String, Integer> collector) {
    4. String[] words = value.split("[^a-zA-Z]");
    5. for (String word : words) {
    6. collector.emit(word, 1);
    7. }
    8. }
    9. }
  2. Reducer对象计算统计所有单词的使用情况。

    1. public class WordReducer implements RReducer<String, Integer> {
    2. @Override
    3. public Integer reduce(String reducedKey, Iterator<Integer> iter) {
    4. int sum = 0;
    5. while (iter.hasNext()) {
    6. Integer i = (Integer) iter.next();
    7. sum += i;
    8. }
    9. return sum;
    10. }
    11. }
  3. Collator对象统计所有单词的使用情况。

    1. public class WordCollator implements RCollator<String, Integer, Integer> {
    2. @Override
    3. public Integer collate(Map<String, Integer> resultMap) {
    4. int result = 0;
    5. for (Integer count : resultMap.values()) {
    6. result += count;
    7. }
    8. return result;
    9. }
    10. }
  4. 把上面的各个对象串起来使用:

    1. RMap<String, String> map = redisson.getMap("wordsMap");
    2. map.put("line1", "Alice was beginning to get very tired");
    3. map.put("line2", "of sitting by her sister on the bank and");
    4. map.put("line3", "of having nothing to do once or twice she");
    5. map.put("line4", "had peeped into the book her sister was reading");
    6. map.put("line5", "but it had no pictures or conversations in it");
    7. map.put("line6", "and what is the use of a book");
    8. map.put("line7", "thought Alice without pictures or conversation");
    9. RMapReduce<String, String, String, Integer> mapReduce
    10. = map.<String, Integer>mapReduce()
    11. .mapper(new WordMapper())
    12. .reducer(new WordReducer());
    13. // 统计词频
    14. Map<String, Integer> mapToNumber = mapReduce.execute();
    15. // 统计字数
    16. Integer totalWordsAmount = mapReduce.execute(new WordCollator());