flink 学习(五)hdfs 作为数据源

本文档展示了如何在Apache Flink中引入Hadoop依赖,创建HDFS文件,然后通过Flink读取并处理这些数据。具体步骤包括添加Hadoop和Flink的依赖,将数据写入HDFS,最后编写Flink作业从HDFS读取文件,进行数据扁平化、映射、分组和求和操作。
摘要由CSDN通过智能技术生成

1.引入依赖

<!-- https://mvnrepository.com/artifact/org.apache.flink/flink-hadoop-compatibility -->
<dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-hadoop-compatibility_2.12</artifactId>
    <version>1.14.4</version>
    <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-client -->
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>3.3.2</version>
</dependency>

2.创建hdfs文件

[root@cloudtest02 hadoop-3.2.0]# cat test.txt
java,python,c++
java,python,c#

创建目录

[root@cloudtest02 hadoop-3.2.0]# hdfs dfs -mkdir -p /root/hadoop

将文件放进目录

[root@cloudtest02 hadoop-3.2.0]# hdfs dfs -put test.txt /root/hadoop

3.从hdfs读取数据

	@Test
    public void fromHdfsTest() throws Exception {
        // 执行环境
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //添加 hdfs 数据源
        env.readTextFile("hdfs://172.16.10.159:9000/root/input/test.txt")
                //扁平化
                .flatMap(new FlatMapFunction<String, String>() {
                    @Override
                    public void flatMap(String value, Collector<String> out) throws Exception {
                        Arrays.stream(value.split(",")).forEach(v -> out.collect(v));
                    }
                })
                //映射
                .map(new MapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String value) throws Exception {
                        return Tuple2.of(value, 1);
                    }
                })
                //分组
                .groupBy((KeySelector<Tuple2<String, Integer>, String>) value -> value.f0)
                //求和
                .reduce((v1, v2) -> new Tuple2<String, Integer>(v1.f0, v1.f1 + v2.f1))
                //打印结果
                .print();
    }

结果:

(c#,1)
(java,3)
(python,3)
(c++,2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_lrs

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

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

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

打赏作者

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

抵扣说明:

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

余额充值