当前位置:   article > 正文

Flink 输出至 Redis_flink-redis

flink-redis

【1】引入第三方Bahir提供的Flink-redis相关依赖包

<!-- https://mvnrepository.com/artifact/org.apache.bahir/flink-connector-redis -->
<dependency>
    <groupId>org.apache.bahir</groupId>
    <artifactId>flink-connector-redis_2.11</artifactId>
    <version>1.0</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

【2】Flink连接Redis并输出Sink处理结果

package com.zzx.flink

import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.redis.RedisSink
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig
import org.apache.flink.streaming.connectors.redis.common.mapper.{RedisCommand, RedisCommandDescription, RedisMapper}

object RedisSinkTest {
  def main(args: Array[String]): Unit = {
    // 创建一个流处理执行环境
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    //从文件中读取数据并转换为 类
    val inputStreamFromFile: DataStream[String] = env.readTextFile("E:\\Project\\flink\\src\\main\\resources\\wordcount.txt")
    //转换  SensorReading为用户自定义的类,是从文件转换而来的
    val dataStream: DataStream[SensorReading] = inputStreamFromFile
      .map( data => {
        var dataArray = data.split(",")
        SensorReading(dataArray(0),dataArray(1).toLong,dataArray(2).toDouble)
      })
    //定义一个 redis 的配置类 继承了FlinkJedisConfigBase 正是 SensorReading需要传入的参数,底层将有些数据保存成了状态数据。
    val conf = new FlinkJedisPoolConfig.Builder().setHost("192.168.52.131").setPort(6379).setPassword("zzx").build()
    //定义 RedisMapper 数据保存的类型
    val myMapper = new RedisMapper[SensorReading] {
      //定义保存数据到 redis的命令,hset table key value
      override def getCommandDescription: RedisCommandDescription = {
        // hset tablesname
        new RedisCommandDescription(RedisCommand.HSET , "sensor_temp")
      }
      //设置key
      override def getKeyFromData(data: SensorReading): String = data.id
      //设置value
      override def getValueFromData(data: SensorReading): String = data.temperature.toString
    }
    dataStream.addSink(new RedisSink[SensorReading](conf,myMapper))

    env.execute("Redis Sink test")
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

查看源码可知RedisSink是继承自RichSinkFunction<IN>

public class RedisSink<IN> extends RichSinkFunction<IN> {
  • 1

【3】查看Redis输出信息
[点击并拖拽以移动]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/751757
推荐阅读
相关标签
  

闽ICP备14008679号