streaming通过sql对hbase写入数据

代码

package com.badou.streaming

import org.apache.hadoop.hbase._
import org.apache.hadoop.hbase.client._
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka.KafkaUtils

object HbaseHandler {
  def insert(row: String, column: String, value: String) {
    // Hbase配置
    val tableName = "sparkstream_kafkahbase_table" // 定义表名
    val hbaseConf = HBaseConfiguration.create()
    hbaseConf.set("hbase.zookeeper.quorum", "master,slave1,slave2")
    hbaseConf.set("hbase.zookeeper.property.clientPort", "2181")
    hbaseConf.set("hbase.defaults.for.version.skip", "true")
    val hTable = new HTable(hbaseConf, tableName)
    val thePut = new Put(row.getBytes)
    thePut.add("info".getBytes,column.getBytes,value.getBytes)
    hTable.setAutoFlush(false, false)
    // 写入数据缓存
    hTable.setWriteBufferSize(3*1024*1024)
    hTable.put(thePut)
    // 提交
    hTable.flushCommits()
  }
}

object kafkaStreamHbase {
  def main(args: Array[String]) {

    val zkQuorum = "master:2181,slave1:2181,slave2:2181"
    val group = "group_1"
    val topics = "topic_1013"
    val numThreads = 1
    var output="hdfs://master:9000/stream_out/spark-log.txt"

    val sparkConf = new SparkConf().setAppName("kafkaStreamHbase").setMaster("local[2]")
    val ssc =  new StreamingContext(sparkConf, Seconds(10))
    ssc.checkpoint("hdfs://master:9000/hdfs_checkpoint")

    val topicpMap = topics.split(",").map((_,numThreads.toInt)).toMap
    val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicpMap).map(_._2)
    // lines.print()
    // lines.saveAsTextFiles("hdfs://master:9000/stream_out/sparkstreaming_hbasetest.log")
    val line = lines.flatMap(_.split("\n"))
    val words = line.map(_.split("\\|"))
    words.foreachRDD(rdd => {
      rdd.foreachPartition(partitionOfRecords => {
        partitionOfRecords.foreach(pair => {
          val key = pair(0)
          val col = pair(1)
          val value = pair(2)
          println(key + "_" + col + " : " + value)
          HbaseHandler.insert(key, col, value)
        })
      })
    })
    ssc.start()
    ssc.awaitTermination()
  }
}

补充
object SQLContextSingleton {
  @transient  private var instance: SQLContext = _
  def getInstance(sparkContext: SparkContext): SQLContext = {
    if (instance == null) {
      instance = new SQLContext(sparkContext)
    }
    instance
  }
}

测试

结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个基本的Spark程序,用于消费Kafka数据并将其写入HBase中: ```scala import org.apache.spark.SparkConf import org.apache.spark.streaming.{Seconds, StreamingContext} import org.apache.spark.streaming.kafka.KafkaUtils import org.apache.spark.sql.SparkSession import org.apache.spark.sql.functions._ import org.apache.hadoop.hbase.{HBaseConfiguration, TableName} import org.apache.hadoop.hbase.client.{Connection, ConnectionFactory, Put} import org.apache.hadoop.hbase.util.Bytes object KafkaToHBase { def main(args: Array[String]) { val conf = new SparkConf().setAppName("KafkaToHBase") val ssc = new StreamingContext(conf, Seconds(5)) val kafkaParams = Map("metadata.broker.list" -> "localhost:9092") val topics = Set("my-topic") val stream = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder]( ssc, kafkaParams, topics) val spark = SparkSession.builder().appName("KafkaToHBase").getOrCreate() stream.foreachRDD { rdd => if (!rdd.isEmpty()) { val df = spark.read.json(rdd.map(_._2)) val hbaseConf = HBaseConfiguration.create() val connection: Connection = ConnectionFactory.createConnection(hbaseConf) val table = connection.getTable(TableName.valueOf("my-table")) df.select("id", "name", "age").foreach { row => val put = new Put(Bytes.toBytes(row.getAs[String]("id"))) put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes(row.getAs[String]("name"))) put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("age"), Bytes.toBytes(row.getAs[Int]("age"))) table.put(put) } table.close() connection.close() } } ssc.start() ssc.awaitTermination() } } ``` 这个程序假设Kafka主题中的消息是JSON格式的,并将其读入一个Spark DataFrame中。然后,它将DataFrame的每一行写入HBase表中。在此示例中,HBase表中有一个名为“cf”的列族,包含两个列:“name”和“age”。您需要将程序中的“my-topic”和“my-table”替换为您自己的Kafka主题和HBase表名。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

曾牛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值