Storm 集成 Redis 详解

一、简介

Storm-Redis 提供了 Storm 与 Redis 的集成支持,你只需要引入对应的依赖即可使用:

  1. <dependency>
  2. <groupId>org.apache.storm</groupId>
  3. <artifactId>storm-redis</artifactId>
  4. <version>${storm.version}</version>
  5. <type>jar</type>
  6. </dependency>

Storm-Redis 使用 Jedis 为 Redis 客户端,并提供了如下三个基本的 Bolt 实现:

  • RedisLookupBolt:从 Redis 中查询数据;
  • RedisStoreBolt:存储数据到 Redis;
  • RedisFilterBolt : 查询符合条件的数据;

RedisLookupBoltRedisStoreBoltRedisFilterBolt 均继承自 AbstractRedisBolt 抽象类。我们可以通过继承该抽象类,实现自定义 RedisBolt,进行功能的拓展。

二、集成案例

2.1 项目结构

这里首先给出一个集成案例:进行词频统计并将最后的结果存储到 Redis。项目结构如下:

Storm 集成 Redis 详解 - 图1

用例源码下载地址:storm-redis-integration

2.2 项目依赖

项目主要依赖如下:

  1. <properties>
  2. <storm.version>1.2.2</storm.version>
  3. </properties>
  4. <dependencies>
  5. <dependency>
  6. <groupId>org.apache.storm</groupId>
  7. <artifactId>storm-core</artifactId>
  8. <version>${storm.version}</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.apache.storm</groupId>
  12. <artifactId>storm-redis</artifactId>
  13. <version>${storm.version}</version>
  14. </dependency>
  15. </dependencies>

2.3 DataSourceSpout

  1. /**
  2. * 产生词频样本的数据源
  3. */
  4. public class DataSourceSpout extends BaseRichSpout {
  5. private List<String> list = Arrays.asList("Spark", "Hadoop", "HBase", "Storm", "Flink", "Hive");
  6. private SpoutOutputCollector spoutOutputCollector;
  7. @Override
  8. public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
  9. this.spoutOutputCollector = spoutOutputCollector;
  10. }
  11. @Override
  12. public void nextTuple() {
  13. // 模拟产生数据
  14. String lineData = productData();
  15. spoutOutputCollector.emit(new Values(lineData));
  16. Utils.sleep(1000);
  17. }
  18. @Override
  19. public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
  20. outputFieldsDeclarer.declare(new Fields("line"));
  21. }
  22. /**
  23. * 模拟数据
  24. */
  25. private String productData() {
  26. Collections.shuffle(list);
  27. Random random = new Random();
  28. int endIndex = random.nextInt(list.size()) % (list.size()) + 1;
  29. return StringUtils.join(list.toArray(), "\t", 0, endIndex);
  30. }
  31. }

产生的模拟数据格式如下:

  1. Spark HBase
  2. Hive Flink Storm Hadoop HBase Spark
  3. Flink
  4. HBase Storm
  5. HBase Hadoop Hive Flink
  6. HBase Flink Hive Storm
  7. Hive Flink Hadoop
  8. HBase Hive
  9. Hadoop Spark HBase Storm

2.4 SplitBolt

  1. /**
  2. * 将每行数据按照指定分隔符进行拆分
  3. */
  4. public class SplitBolt extends BaseRichBolt {
  5. private OutputCollector collector;
  6. @Override
  7. public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
  8. this.collector = collector;
  9. }
  10. @Override
  11. public void execute(Tuple input) {
  12. String line = input.getStringByField("line");
  13. String[] words = line.split("\t");
  14. for (String word : words) {
  15. collector.emit(new Values(word, String.valueOf(1)));
  16. }
  17. }
  18. @Override
  19. public void declareOutputFields(OutputFieldsDeclarer declarer) {
  20. declarer.declare(new Fields("word", "count"));
  21. }
  22. }

2.5 CountBolt

  1. /**
  2. * 进行词频统计
  3. */
  4. public class CountBolt extends BaseRichBolt {
  5. private Map<String, Integer> counts = new HashMap<>();
  6. private OutputCollector collector;
  7. @Override
  8. public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
  9. this.collector=collector;
  10. }
  11. @Override
  12. public void execute(Tuple input) {
  13. String word = input.getStringByField("word");
  14. Integer count = counts.get(word);
  15. if (count == null) {
  16. count = 0;
  17. }
  18. count++;
  19. counts.put(word, count);
  20. // 输出
  21. collector.emit(new Values(word, String.valueOf(count)));
  22. }
  23. @Override
  24. public void declareOutputFields(OutputFieldsDeclarer declarer) {
  25. declarer.declare(new Fields("word", "count"));
  26. }
  27. }

2.6 WordCountStoreMapper

实现 RedisStoreMapper 接口,定义 tuple 与 Redis 中数据的映射关系:即需要指定 tuple 中的哪个字段为 key,哪个字段为 value,并且存储到 Redis 的何种数据结构中。

  1. /**
  2. * 定义 tuple 与 Redis 中数据的映射关系
  3. */
  4. public class WordCountStoreMapper implements RedisStoreMapper {
  5. private RedisDataTypeDescription description;
  6. private final String hashKey = "wordCount";
  7. public WordCountStoreMapper() {
  8. description = new RedisDataTypeDescription(
  9. RedisDataTypeDescription.RedisDataType.HASH, hashKey);
  10. }
  11. @Override
  12. public RedisDataTypeDescription getDataTypeDescription() {
  13. return description;
  14. }
  15. @Override
  16. public String getKeyFromTuple(ITuple tuple) {
  17. return tuple.getStringByField("word");
  18. }
  19. @Override
  20. public String getValueFromTuple(ITuple tuple) {
  21. return tuple.getStringByField("count");
  22. }
  23. }

2.7 WordCountToRedisApp

  1. /**
  2. * 进行词频统计 并将统计结果存储到 Redis 中
  3. */
  4. public class WordCountToRedisApp {
  5. private static final String DATA_SOURCE_SPOUT = "dataSourceSpout";
  6. private static final String SPLIT_BOLT = "splitBolt";
  7. private static final String COUNT_BOLT = "countBolt";
  8. private static final String STORE_BOLT = "storeBolt";
  9. //在实际开发中这些参数可以将通过外部传入 使得程序更加灵活
  10. private static final String REDIS_HOST = "192.168.200.226";
  11. private static final int REDIS_PORT = 6379;
  12. public static void main(String[] args) {
  13. TopologyBuilder builder = new TopologyBuilder();
  14. builder.setSpout(DATA_SOURCE_SPOUT, new DataSourceSpout());
  15. // split
  16. builder.setBolt(SPLIT_BOLT, new SplitBolt()).shuffleGrouping(DATA_SOURCE_SPOUT);
  17. // count
  18. builder.setBolt(COUNT_BOLT, new CountBolt()).shuffleGrouping(SPLIT_BOLT);
  19. // save to redis
  20. JedisPoolConfig poolConfig = new JedisPoolConfig.Builder()
  21. .setHost(REDIS_HOST).setPort(REDIS_PORT).build();
  22. RedisStoreMapper storeMapper = new WordCountStoreMapper();
  23. RedisStoreBolt storeBolt = new RedisStoreBolt(poolConfig, storeMapper);
  24. builder.setBolt(STORE_BOLT, storeBolt).shuffleGrouping(COUNT_BOLT);
  25. // 如果外部传参 cluster 则代表线上环境启动否则代表本地启动
  26. if (args.length > 0 && args[0].equals("cluster")) {
  27. try {
  28. StormSubmitter.submitTopology("ClusterWordCountToRedisApp", new Config(), builder.createTopology());
  29. } catch (AlreadyAliveException | InvalidTopologyException | AuthorizationException e) {
  30. e.printStackTrace();
  31. }
  32. } else {
  33. LocalCluster cluster = new LocalCluster();
  34. cluster.submitTopology("LocalWordCountToRedisApp",
  35. new Config(), builder.createTopology());
  36. }
  37. }
  38. }

2.8 启动测试

可以用直接使用本地模式运行,也可以打包后提交到服务器集群运行。本仓库提供的源码默认采用 maven-shade-plugin 进行打包,打包命令如下:

  1. # mvn clean package -D maven.test.skip=true

启动后,查看 Redis 中的数据:

Storm 集成 Redis 详解 - 图2

三、storm-redis 实现原理

3.1 AbstractRedisBolt

RedisLookupBoltRedisStoreBoltRedisFilterBolt 均继承自 AbstractRedisBolt 抽象类,和我们自定义实现 Bolt 一样,AbstractRedisBolt 间接继承自 BaseRichBolt

Storm 集成 Redis 详解 - 图3

AbstractRedisBolt 中比较重要的是 prepare 方法,在该方法中通过外部传入的 jedis 连接池配置 ( jedisPoolConfig/jedisClusterConfig) 创建用于管理 Jedis 实例的容器 JedisCommandsInstanceContainer

  1. public abstract class AbstractRedisBolt extends BaseTickTupleAwareRichBolt {
  2. protected OutputCollector collector;
  3. private transient JedisCommandsInstanceContainer container;
  4. private JedisPoolConfig jedisPoolConfig;
  5. private JedisClusterConfig jedisClusterConfig;
  6. ......
  7. @Override
  8. public void prepare(Map map, TopologyContext topologyContext, OutputCollector collector) {
  9. // FIXME: stores map (stormConf), topologyContext and expose these to derived classes
  10. this.collector = collector;
  11. if (jedisPoolConfig != null) {
  12. this.container = JedisCommandsContainerBuilder.build(jedisPoolConfig);
  13. } else if (jedisClusterConfig != null) {
  14. this.container = JedisCommandsContainerBuilder.build(jedisClusterConfig);
  15. } else {
  16. throw new IllegalArgumentException("Jedis configuration not found");
  17. }
  18. }
  19. .......
  20. }

JedisCommandsInstanceContainerbuild() 方法如下,实际上就是创建 JedisPool 或 JedisCluster 并传入容器中。

  1. public static JedisCommandsInstanceContainer build(JedisPoolConfig config) {
  2. JedisPool jedisPool = new JedisPool(DEFAULT_POOL_CONFIG, config.getHost(), config.getPort(), config.getTimeout(), config.getPassword(), config.getDatabase());
  3. return new JedisContainer(jedisPool);
  4. }
  5. public static JedisCommandsInstanceContainer build(JedisClusterConfig config) {
  6. JedisCluster jedisCluster = new JedisCluster(config.getNodes(), config.getTimeout(), config.getTimeout(), config.getMaxRedirections(), config.getPassword(), DEFAULT_POOL_CONFIG);
  7. return new JedisClusterContainer(jedisCluster);
  8. }

3.2 RedisStoreBolt和RedisLookupBolt

RedisStoreBolt 中比较重要的是 process 方法,该方法主要从 storeMapper 中获取传入 key/value 的值,并按照其存储类型 dataType 调用 jedisCommand 的对应方法进行存储。

RedisLookupBolt 的实现基本类似,从 lookupMapper 中获取传入的 key 值,并进行查询操作。

  1. public class RedisStoreBolt extends AbstractRedisBolt {
  2. private final RedisStoreMapper storeMapper;
  3. private final RedisDataTypeDescription.RedisDataType dataType;
  4. private final String additionalKey;
  5. public RedisStoreBolt(JedisPoolConfig config, RedisStoreMapper storeMapper) {
  6. super(config);
  7. this.storeMapper = storeMapper;
  8. RedisDataTypeDescription dataTypeDescription = storeMapper.getDataTypeDescription();
  9. this.dataType = dataTypeDescription.getDataType();
  10. this.additionalKey = dataTypeDescription.getAdditionalKey();
  11. }
  12. public RedisStoreBolt(JedisClusterConfig config, RedisStoreMapper storeMapper) {
  13. super(config);
  14. this.storeMapper = storeMapper;
  15. RedisDataTypeDescription dataTypeDescription = storeMapper.getDataTypeDescription();
  16. this.dataType = dataTypeDescription.getDataType();
  17. this.additionalKey = dataTypeDescription.getAdditionalKey();
  18. }
  19. @Override
  20. public void process(Tuple input) {
  21. String key = storeMapper.getKeyFromTuple(input);
  22. String value = storeMapper.getValueFromTuple(input);
  23. JedisCommands jedisCommand = null;
  24. try {
  25. jedisCommand = getInstance();
  26. switch (dataType) {
  27. case STRING:
  28. jedisCommand.set(key, value);
  29. break;
  30. case LIST:
  31. jedisCommand.rpush(key, value);
  32. break;
  33. case HASH:
  34. jedisCommand.hset(additionalKey, key, value);
  35. break;
  36. case SET:
  37. jedisCommand.sadd(key, value);
  38. break;
  39. case SORTED_SET:
  40. jedisCommand.zadd(additionalKey, Double.valueOf(value), key);
  41. break;
  42. case HYPER_LOG_LOG:
  43. jedisCommand.pfadd(key, value);
  44. break;
  45. case GEO:
  46. String[] array = value.split(":");
  47. if (array.length != 2) {
  48. throw new IllegalArgumentException("value structure should be longitude:latitude");
  49. }
  50. double longitude = Double.valueOf(array[0]);
  51. double latitude = Double.valueOf(array[1]);
  52. jedisCommand.geoadd(additionalKey, longitude, latitude, key);
  53. break;
  54. default:
  55. throw new IllegalArgumentException("Cannot process such data type: " + dataType);
  56. }
  57. collector.ack(input);
  58. } catch (Exception e) {
  59. this.collector.reportError(e);
  60. this.collector.fail(input);
  61. } finally {
  62. returnInstance(jedisCommand);
  63. }
  64. }
  65. .........
  66. }

3.3 JedisCommands

JedisCommands 接口中定义了所有的 Redis 客户端命令,它有以下三个实现类,分别是 Jedis、JedisCluster、ShardedJedis。Strom 中主要使用前两种实现类,具体调用哪一个实现类来执行命令,由传入的是 jedisPoolConfig 还是 jedisClusterConfig 来决定。

Storm 集成 Redis 详解 - 图4

3.4 RedisMapper 和 TupleMapper

RedisMapper 和 TupleMapper 定义了 tuple 和 Redis 中的数据如何进行映射转换。

Storm 集成 Redis 详解 - 图5

1. TupleMapper

TupleMapper 主要定义了两个方法:

  • getKeyFromTuple(ITuple tuple): 从 tuple 中获取那个字段作为 Key;

  • getValueFromTuple(ITuple tuple):从 tuple 中获取那个字段作为 Value;

2. RedisMapper

定义了获取数据类型的方法 getDataTypeDescription(),RedisDataTypeDescription 中 RedisDataType 枚举类定义了所有可用的 Redis 数据类型:

  1. public class RedisDataTypeDescription implements Serializable {
  2. public enum RedisDataType { STRING, HASH, LIST, SET, SORTED_SET, HYPER_LOG_LOG, GEO }
  3. ......
  4. }

3. RedisStoreMapper

RedisStoreMapper 继承 TupleMapper 和 RedisMapper 接口,用于数据存储时,没有定义额外方法。

4. RedisLookupMapper

RedisLookupMapper 继承 TupleMapper 和 RedisMapper 接口:

  • 定义了 declareOutputFields 方法,声明输出的字段。
  • 定义了 toTuple 方法,将查询结果组装为 Storm 的 Values 的集合,并用于发送。

下面的例子表示从输入 Tuple 的获取 word 字段作为 key,使用 RedisLookupBolt 进行查询后,将 key 和查询结果 value 组装为 values 并发送到下一个处理单元。

  1. class WordCountRedisLookupMapper implements RedisLookupMapper {
  2. private RedisDataTypeDescription description;
  3. private final String hashKey = "wordCount";
  4. public WordCountRedisLookupMapper() {
  5. description = new RedisDataTypeDescription(
  6. RedisDataTypeDescription.RedisDataType.HASH, hashKey);
  7. }
  8. @Override
  9. public List<Values> toTuple(ITuple input, Object value) {
  10. String member = getKeyFromTuple(input);
  11. List<Values> values = Lists.newArrayList();
  12. values.add(new Values(member, value));
  13. return values;
  14. }
  15. @Override
  16. public void declareOutputFields(OutputFieldsDeclarer declarer) {
  17. declarer.declare(new Fields("wordName", "count"));
  18. }
  19. @Override
  20. public RedisDataTypeDescription getDataTypeDescription() {
  21. return description;
  22. }
  23. @Override
  24. public String getKeyFromTuple(ITuple tuple) {
  25. return tuple.getStringByField("word");
  26. }
  27. @Override
  28. public String getValueFromTuple(ITuple tuple) {
  29. return null;
  30. }
  31. }

5. RedisFilterMapper

RedisFilterMapper 继承 TupleMapper 和 RedisMapper 接口,用于查询数据时,定义了 declareOutputFields 方法,声明输出的字段。如下面的实现:

  1. @Override
  2. public void declareOutputFields(OutputFieldsDeclarer declarer) {
  3. declarer.declare(new Fields("wordName", "count"));
  4. }

四、自定义RedisBolt实现词频统计

4.1 实现原理

自定义 RedisBolt:主要利用 Redis 中哈希结构的 hincrby key field 命令进行词频统计。在 Redis 中 hincrby 的执行效果如下。hincrby 可以将字段按照指定的值进行递增,如果该字段不存在的话,还会新建该字段,并赋值为 0。通过这个命令可以非常轻松的实现词频统计功能。

  1. redis> HSET myhash field 5
  2. (integer) 1
  3. redis> HINCRBY myhash field 1
  4. (integer) 6
  5. redis> HINCRBY myhash field -1
  6. (integer) 5
  7. redis> HINCRBY myhash field -10
  8. (integer) -5
  9. redis>

4.2 项目结构

Storm 集成 Redis 详解 - 图6

4.3 自定义RedisBolt的代码实现

  1. /**
  2. * 自定义 RedisBolt 利用 Redis 的哈希数据结构的 hincrby key field 命令进行词频统计
  3. */
  4. public class RedisCountStoreBolt extends AbstractRedisBolt {
  5. private final RedisStoreMapper storeMapper;
  6. private final RedisDataTypeDescription.RedisDataType dataType;
  7. private final String additionalKey;
  8. public RedisCountStoreBolt(JedisPoolConfig config, RedisStoreMapper storeMapper) {
  9. super(config);
  10. this.storeMapper = storeMapper;
  11. RedisDataTypeDescription dataTypeDescription = storeMapper.getDataTypeDescription();
  12. this.dataType = dataTypeDescription.getDataType();
  13. this.additionalKey = dataTypeDescription.getAdditionalKey();
  14. }
  15. @Override
  16. protected void process(Tuple tuple) {
  17. String key = storeMapper.getKeyFromTuple(tuple);
  18. String value = storeMapper.getValueFromTuple(tuple);
  19. JedisCommands jedisCommand = null;
  20. try {
  21. jedisCommand = getInstance();
  22. if (dataType == RedisDataTypeDescription.RedisDataType.HASH) {
  23. jedisCommand.hincrBy(additionalKey, key, Long.valueOf(value));
  24. } else {
  25. throw new IllegalArgumentException("Cannot process such data type for Count: " + dataType);
  26. }
  27. collector.ack(tuple);
  28. } catch (Exception e) {
  29. this.collector.reportError(e);
  30. this.collector.fail(tuple);
  31. } finally {
  32. returnInstance(jedisCommand);
  33. }
  34. }
  35. @Override
  36. public void declareOutputFields(OutputFieldsDeclarer declarer) {
  37. }
  38. }

4.4 CustomRedisCountApp

  1. /**
  2. * 利用自定义的 RedisBolt 实现词频统计
  3. */
  4. public class CustomRedisCountApp {
  5. private static final String DATA_SOURCE_SPOUT = "dataSourceSpout";
  6. private static final String SPLIT_BOLT = "splitBolt";
  7. private static final String STORE_BOLT = "storeBolt";
  8. private static final String REDIS_HOST = "192.168.200.226";
  9. private static final int REDIS_PORT = 6379;
  10. public static void main(String[] args) {
  11. TopologyBuilder builder = new TopologyBuilder();
  12. builder.setSpout(DATA_SOURCE_SPOUT, new DataSourceSpout());
  13. // split
  14. builder.setBolt(SPLIT_BOLT, new SplitBolt()).shuffleGrouping(DATA_SOURCE_SPOUT);
  15. // save to redis and count
  16. JedisPoolConfig poolConfig = new JedisPoolConfig.Builder()
  17. .setHost(REDIS_HOST).setPort(REDIS_PORT).build();
  18. RedisStoreMapper storeMapper = new WordCountStoreMapper();
  19. RedisCountStoreBolt countStoreBolt = new RedisCountStoreBolt(poolConfig, storeMapper);
  20. builder.setBolt(STORE_BOLT, countStoreBolt).shuffleGrouping(SPLIT_BOLT);
  21. // 如果外部传参 cluster 则代表线上环境启动,否则代表本地启动
  22. if (args.length > 0 && args[0].equals("cluster")) {
  23. try {
  24. StormSubmitter.submitTopology("ClusterCustomRedisCountApp", new Config(), builder.createTopology());
  25. } catch (AlreadyAliveException | InvalidTopologyException | AuthorizationException e) {
  26. e.printStackTrace();
  27. }
  28. } else {
  29. LocalCluster cluster = new LocalCluster();
  30. cluster.submitTopology("LocalCustomRedisCountApp",
  31. new Config(), builder.createTopology());
  32. }
  33. }
  34. }

参考资料

  1. Storm Redis Integration