flink数据写入hive实现demo

        首先呢,flink写入hive已经在1.10就实现了,但是我们这么用呢,其实是大多数公司不得已的情况,也是慢慢转型而来的一个适中的使用情况,Apache也为我们考虑提供了支持,帮我们再分布式环境、流计算的今天提供了更好的帮助。感谢这些社区贡献者和大佬的们研究分享。以下是实现的一个小demo,大家共同分析学习,有问题交流学习。

注意: 在本地环境读数据要是可以的话,写数据就一定可以的。写的时候需要注意服务器上的环境,主要是权限和jar依赖。

1.代码实现

1.1使用tableEvironment读取catlog配置,然后sql操作hive

1.先来个最基本的测试demo,测试通过在看后面的,这个是从hive表里读取数据然后写入hive

package flink.java.connector.hive.write;
import flink.java.utils.HiveResourceInfo;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.connector.jdbc.JdbcInputFormat;
import org.apache.flink.table.api.*;
import org.apache.flink.table.api.bridge.java.BatchTableEnvironment;
import org.apache.flink.table.catalog.hive.HiveCatalog;
import org.apache.flink.types.Row;


import java.util.List;
import java.util.Properties;

import static org.apache.flink.table.api.Expressions.$;


public class Hive2Hive {
    public static void main(String[] args) throws Exception {

        EnvironmentSettings settings = EnvironmentSettings.newInstance().inBatchMode().build();
        TableEnvironment tableEnv = TableEnvironment.create(settings);
        Properties hiveConf = HiveResourceInfo.getHiveConf();

        HiveCatalog hive = new HiveCatalog(hiveConf.getProperty("CATALOG.NAME"),
                hiveConf.getProperty("CATALOG.DB"),
                hiveConf.getProperty("CATALOG.HIVECONFDIR"));
        tableEnv.registerCatalog("myhive", hive);
        tableEnv.useCatalog("myhive");
        tableEnv.getConfig().setSqlDialect(SqlDialect.HIVE);
        String hiveSql = "create external table  fs_tables (" +
                "  id string," +
                "  name String" +
                ") partitioned by (dt string) " +
                "stored as orc " +
                "tblproperties (" +
                "  'partition.time-extractor.timestamp-pattern'='$dt'," +
                "  'sink.partition-commit.delay'='0s'," +
                "  'sink.partition-commit.trigger'='partition-time'," +
                "  'sink.partition-commit.policy.kind'='metastore'" +
                ")";
        tableEnv.executeSql(hiveSql);
//        Table result = table.groupBy($("age")).select($("id"), $("name"), $("age"));
//        Table table = tableEnv.sqlQuery("select id,name,age from test.hive_test7  where age > 18");

        tableEnv.executeSql("insert into  fs_tables select id,name,age from test.hive_test7 where age > 18 ");

    }

}


1.2使用jdbc的方式读取hive的dataset数据,然后使用tableEvironment读取catlog配置,写入hive

注意,我们不能直接使用batchTableEnvironment的方式,将批数据转成table然后使用table的API直接insert到hive,这两种方式的table是不一样的,如果是使用batchTab ,那么久必须使用batchTableSink或者OutputFormatTableSink 。

所以,如果我们是读出来的批数据,如果是数据量不是很大,那么可以直接放到一个集合里,然后使用table加载到表中,然后使用tableEnvrionment的方式去操作,很香;如果数据量很大那么使用流的方式去处理吧,每个版本都有很大的变化,在flink1.10才是加入对hive的DDL DML,我们是基于1.11.1,所以可以结合当前版本和官网的说明自己来根据当前业务来定义。

public static void main(String[] args) throws Exception {

        EnvironmentSettings settings = EnvironmentSettings.newInstance().inBatchMode().build();
        TableEnvironment tableEnv = TableEnvironment.create(settings);
        Properties hiveConf = HiveResourceInfo.getHiveConf();
        //读取catalog配置
        HiveCatalog hive = new HiveCatalog(
                hiveConf.getProperty("CATALOG.NAME"),
                hiveConf.getProperty("CATALOG.DB"),
                hiveConf.getProperty("CATALOG.HIVECONFDIR")
        );

        tableEnv.registerCatalog("myhive", hive);
        tableEnv.useCatalog("myhive");
        tableEnv.getConfig().setSqlDialect(SqlDialect.HIVE);
        //创建落地表
        String hiveSql = "create external table  fs_tables (" +
                "  id string," +
                "  name String" +
                ") partitioned by (dt string) " +
                "stored as orc " +
                "tblproperties (" +
                "  'partition.time-extractor.timestamp-pattern'='$dt'," +
                "  'sink.partition-commit.delay'='0s'," +
                "  'sink.partition-commit.trigger'='partition-time'," +
                "  'sink.partition-commit.policy.kind'='metastore'" +
                ")";
        tableEnv.executeSql(hiveSql);
//        Table result = table.groupBy($("age")).select($("id"), $("name"), $("age"));
//        Table table = tableEnv.sqlQuery("select id,name,age from test.hive_test7  where age > 18");
        tableEnv.executeSql("SELECT * FROM Orders");

        //落地数据
        tableEnv.executeSql("insert into  fs_tables select id,name,age from test.hive_test7 where age > 18 ");

配置文件的加载 

package flink.java.utils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.Properties;

public class HiveResourceInfo {

    private static HiveResourceInfo resourceInfo=null;
    private static Properties prop=null;
    private HiveResourceInfo(){}

    public static synchronized Properties getHiveConf() throws Exception {
        if(null == resourceInfo){
            resourceInfo=new HiveResourceInfo();
            InputStream inputStream = HiveResourceInfo.class
                    .getClassLoader()
                    .getResourceAsStream("hiveInfo/hiveConf.properties");

            if (Objects.isNull(inputStream)) {
                throw new Exception("can not read connInfo/hive/hiveConf.properties");
            }
            if(null == prop){
                prop=new Properties();
            }
            pro
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是一个基于Flink消费Kafka并将数据写入Hive的示例代码: ```java import org.apache.flink.api.common.functions.RuntimeContext; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.CheckpointingMode; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.sink.RichSinkFunction; import org.apache.flink.streaming.api.functions.sink.SinkFunction; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; import org.apache.flink.types.Row; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; public class FlinkKafkaToHiveDemo { public static void main(String[] args) throws Exception { // 获取命令行参数 final ParameterTool params = ParameterTool.fromArgs(args); // 设置检查点配置 final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.enableCheckpointing(10000, CheckpointingMode.EXACTLY_ONCE); env.getConfig().setGlobalJobParameters(params); // 设置Kafka配置 Properties kafkaProps = new Properties(); kafkaProps.setProperty("bootstrap.servers", params.get("bootstrap.servers", "localhost:9092")); kafkaProps.setProperty("group.id", params.get("group.id", "my-flink-consumer-group")); // 创建FlinkKafkaConsumer FlinkKafkaConsumer<String> kafkaConsumer = new FlinkKafkaConsumer<>( params.get("topic", "my-kafka-topic"), new SimpleStringSchema(), kafkaProps); // 将Kafka数据换为Flink Table EnvironmentSettings settings = EnvironmentSettings.newInstance().useBlinkPlanner().inStreamingMode().build(); StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env, settings); Table kafkaTable = tableEnv.fromDataStream(env.addSource(kafkaConsumer), "value"); // 将Flink Table写入Hive kafkaTable.executeInsert("my_hive_table"); // 执行Flink作业 env.execute("Flink Kafka to Hive Demo"); } // 定义Hive Sink public static class HiveSink extends RichSinkFunction<Row> { private Connection conn; private PreparedStatement stmt; @Override public void open(Configuration parameters) throws Exception { // 获取Hive连接 Class.forName("org.apache.hive.jdbc.HiveDriver"); conn = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "hive", ""); stmt = conn.prepareStatement("INSERT INTO my_hive_table VALUES(?)"); } @Override public void invoke(Row row, SinkFunction.Context context) throws Exception { // 写入Hive stmt.setString(1, row.getField(0).toString()); stmt.executeUpdate(); } @Override public void close() throws SQLException { // 关闭连接 if (conn != null) { conn.close(); } if (stmt != null) { stmt.close(); } } } } ``` 上面的示例代码使用FlinkKafkaConsumer将Kafka数据换为Flink Table,然后使用executeInsert将Flink Table写入Hive。此外,我们还定义了一个HiveSink来将数据写入Hive。请注意,为了使该作业正常运行,您需要在本地启动一个Hive服务,并创建一个名为“my_hive_table”的表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

꧁꫞ND꫞꧂

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

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

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

打赏作者

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

抵扣说明:

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

余额充值