flink同步数据源数据到redis的方法

本文介绍了如何使用ApacheFlink的StreamExecutionEnvironment从数据库或文件获取数据,然后将其转换为JSON格式并推送到Redis服务器的过程。
摘要由CSDN通过智能技术生成

flink可以实现从支持的数据库或者文件中采集数据到redis中

    public RetDTO pushToRedis(List<RtNode> rtNodesList) throws Exception {
        //开始执行
        String rediskey = "flink:" + UUID.randomUUID();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setRestartStrategy(RestartStrategies.noRestart());
        // 本地环境提交
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        //创建表环境
        Table table = null;
         // 根据自己项目的逻辑编写可执行的Flink语句
        // todo
        // 执行flink语句
        //解析table
        ResolvedSchema resolvedSchema = table.getResolvedSchema();
        List<String> columnNames = resolvedSchema.getColumnNames();

        DataStream<Row> rowDataStream = tableEnv.toChangelogStream(table);
        SingleOutputStreamOperator<Tuple2<String, String>> test = rowDataStream
                .flatMap((FlatMapFunction<Row, Tuple2<String, String>>) (row, collector) -> {
                    JSONObject jsonObject = new JSONObject(true);
                    columnNames.forEach(field -> jsonObject.put(field, null == row.getField(field) ? "" : row.getField(field)));
                    Tuple2<String, String> t = new Tuple2<>(rediskey, jsonObject.toJSONString());
                    collector.collect(t);
                })
                .returns(Types.TUPLE(Types.STRING, Types.STRING));
        //定义redis服务器信息
        FlinkJedisPoolConfig conf = new FlinkJedisPoolConfig.Builder()
                .setHost("127.0.0.1")
                .setPort(6479)
                .setPassword("redis_pwd")
                .setDatabase(0)
                .build();
        test.addSink(new RedisSink<>(conf, new SinkRedisMapper()));
        env.execute();
        return RetDTO.ok().data(rediskey);
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开心编码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值