Spark Streaming接收Kafka数据存储到Hbase

fly
spark
hbase
kafka

主要参考了这篇文章https://yq.aliyun.com/articles/60712([点我])(https://yq.aliyun.com/articles/60712), 不过这篇文章使用的spark貌似是spark1.x的。我这里主要是改为了spark2.x的方式

kafka生产数据

闲话少叙,直接上代码:

  1. import java.util.{Properties, UUID} 


  2. import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord} 

  3. import org.apache.kafka.common.serialization.StringSerializer 


  4. import scala.util.Random 



  5. object KafkaProducerTest { 

  6. def main(args: Array[String]): Unit = { 

  7. val rnd = new Random() 

  8. // val topics = "world" 

  9. val topics = "test" 

  10. val brokers = "localhost:9092" 

  11. val props = new Properties() 

  12. props.put("delete.topic.enable", "true") 

  13. props.put("key.serializer", classOf[StringSerializer]) 

  14. // props.put("value.serializer", "org.apache.kafka.common.serialization.StringDeserializer") 

  15. props.put("value.serializer", classOf[StringSerializer]) 

  16. props.put("bootstrap.servers", brokers) 

  17. //props.put("batch.num.messages","10");//props.put("batch.num.messages","10"); 


  18. //props.put("queue.buffering.max.messages", "20"); 

  19. //linger.ms should be 0~100 ms 

  20. props.put("linger.ms", "50") 

  21. //props.put("block.on.buffer.full", "true"); 

  22. //props.put("max.block.ms", "100000"); 

  23. //batch.size and buffer.memory should be changed with "the kafka message size and message sending speed" 

  24. props.put("batch.size", "16384") 

  25. props.put("buffer.memory", "1638400") 


  26. props.put("queue.buffering.max.messages", "1000000") 

  27. props.put("queue.enqueue.timeout.ms", "20000000") 

  28. props.put("producer.type", "sync") 


  29. val producer = new KafkaProducer[String,String](props) 

  30. for(i <- 1001 to 2000){ 

  31. val key = UUID.randomUUID().toString.substring(0,5) 

  32. val value = "fly_" + i + "_" + key 

  33. producer.send(new ProducerRecord[String, String](topics,key, value))//.get() 





  34. producer.flush() 






生产的数据格式为(key,value) = (uuid, fly_i_key) 的形式

spark streaming 读取kafka并保存到hbase

当kafka里面有数据后,使用spark streaming 读取,并存。直接上代码:

  1. import java.util.UUID 


  2. import org.apache.hadoop.hbase.HBaseConfiguration 

  3. import org.apache.hadoop.hbase.client.{Mutation, Put} 

  4. import org.apache.hadoop.hbase.io.ImmutableBytesWritable 

  5. import org.apache.hadoop.hbase.mapreduce.TableOutputFormat 

  6. import org.apache.hadoop.hbase.util.Bytes 

  7. import org.apache.hadoop.mapred.JobConf 

  8. import org.apache.hadoop.mapreduce.OutputFormat 

  9. import org.apache.kafka.clients.consumer.ConsumerRecord 

  10. import org.apache.kafka.common.serialization.StringDeserializer 

  11. import org.apache.spark.rdd.RDD 

  12. import org.apache.spark.sql.SparkSession 

  13. import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe 

  14. import org.apache.spark.streaming.kafka010.KafkaUtils 

  15. import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent 

  16. import org.apache.spark.streaming.{Seconds, StreamingContext} 


  17. /** 

  18. * spark streaming 写入到hbase 

  19. * Sparkstreaming读取Kafka消息再结合SparkSQL,将结果保存到HBase 

  20. */ 



  21. object OBDSQL { 

  22. case class Person(name: String, age: Int, key: String) 


  23. def main(args: Array[String]): Unit = { 

  24. val spark = SparkSession 

  25. .builder() 

  26. .appName("sparkSql") 

  27. .master("local[4]") 

  28. .getOrCreate() 


  29. val sc = spark.sparkContext 


  30. val ssc = new StreamingContext(sc, Seconds(5)) 


  31. val topics = Array("test") 

  32. val kafkaParams = Map( 

  33. "bootstrap.servers" -> "localhost:9092,anotherhost:9092", 

  34. "key.deserializer" -> classOf[StringDeserializer], 

  35. "value.deserializer" -> classOf[StringDeserializer], 

  36. // "group.id" -> "use_a_separate_group_id_for_each_stream", 

  37. "group.id" -> "use_a_separate_group_id_for_each_stream_fly", 

  38. // "auto.offset.reset" -> "latest", 

  39. "auto.offset.reset" -> "earliest", 

  40. // "auto.offset.reset" -> "none", 

  41. "enable.auto.commit" -> (false: java.lang.Boolean) 




  42. val lines = KafkaUtils.createDirectStream[String, String]( 

  43. ssc, 

  44. PreferConsistent, 

  45. Subscribe[String, String](topics, kafkaParams) 




  46. // lines.map(record => (record.key, record.value)).print() 

  47. // lines.map(record => record.value.split("_")).map(x=> (x(0),x(1), x(2))).print() 


  48. lines.foreachRDD((rdd: RDD[ConsumerRecord[String, String]]) => { 

  49. import spark.implicits._ 

  50. if (!rdd.isEmpty()) { 


  51. // temp table 

  52. rdd.map(_.value.split("_")).map(p => Person(p(0), p(1).trim.toInt, p(2))).toDF.createOrReplaceTempView("temp") 


  53. // use spark sql 

  54. val rs = spark.sql("select * from temp") 


  55. // create hbase conf 

  56. val hconf = HBaseConfiguration.create 

  57. hconf.set("hbase.zookeeper.quorum", "localhost"); //ZKFC 

  58. hconf.set("hbase.zookeeper.property.clientPort", "2181") 

  59. hconf.set("hbase.defaults.for.version.skip", "true") 

  60. hconf.set(TableOutputFormat.OUTPUT_TABLE, "t1") // t1是表名, 表里面有一个列簇 cf1 

  61. hconf.setClass("mapreduce.job.outputformat.class", classOf[TableOutputFormat[String]], classOf[OutputFormat[String, Mutation]]) 

  62. val jobConf = new JobConf(hconf) 


  63. // convert every line to hbase lines 

  64. rs.rdd.map(line => { 

  65. val put = new Put(Bytes.toBytes(UUID.randomUUID().toString.substring(0, 9))) 

  66. put.addColumn(Bytes.toBytes("cf1") 

  67. , Bytes.toBytes("name") 

  68. , Bytes.toBytes(line.get(0).toString) 



  69. put.addColumn(Bytes.toBytes("cf1") 

  70. , Bytes.toBytes("age") 

  71. , Bytes.toBytes(line.get(1).toString) 



  72. put.addColumn(Bytes.toBytes("cf1") 

  73. , Bytes.toBytes("key") 

  74. , Bytes.toBytes(line.get(2).toString) 



  75. (new ImmutableBytesWritable, put) 

  76. }).saveAsNewAPIHadoopDataset(jobConf) 



  77. }) 


  78. lines.map(record => record.value.split("_")).map(x=> (x(0),x(1), x(2))).print() 


  79. ssc start() 

  80. ssc awaitTermination() 







Spark Streaming接收Kafka数据存储到Hbase的更多相关文章

  1. demo1 spark streaming 接收 kafka 数据java代码WordCount示例

    1. 首先启动zookeeper windows上的安装见zk 02之 Windows安装和使用zookeeper 启动后见: 2. 启动kafka windows的安装kafka见Windows上搭 ...

  2. spark streaming 接收 kafka 数据java代码WordCount示例

    http://www.cnblogs.com/gaopeng527/p/4959633.html

  3. Kafka:ZK+Kafka+Spark Streaming集群环境搭建(二十二)Spark Streaming接收流数据及使用窗口函数

    官网文档:<http://spark.apache.org/docs/latest/streaming-programming-guide.html#a-quick-example> Sp ...

  4. spark streaming 接收kafka消息之五 -- spark streaming 和 kafka 的对接总结

    Spark streaming 和kafka 处理确保消息不丢失的总结 接入kafka 我们前面的1到4 都在说 spark streaming 接入 kafka 消息的事情.讲了两种接入方式,以及s ...

  5. spark streaming 接收kafka消息之四 -- 运行在 worker 上的 receiver

    使用分布式receiver来获取数据使用 WAL 来实现 exactly-once 操作: conf.set("spark.streaming.receiver.writeAheadLog. ...

  6. spark streaming 接收kafka消息之一 -- 两种接收方式

    源码分析的spark版本是1.6. 首先,先看一下 org.apache.spark.streaming.dstream.InputDStream 的 类说明: This is the abstrac ...

  7. spark streaming 接收kafka消息之二 -- 运行在driver端的receiver

    先从源码来深入理解一下 DirectKafkaInputDStream 的将 kafka 作为输入流时,如何确保 exactly-once 语义. val stream: InputDStream[( ...

  8. spark streaming 接收kafka消息之三 -- kafka broker 如何处理 fetch 请求

    首先看一下 KafkaServer 这个类的声明: Represents the lifecycle of a single Kafka broker. Handles all functionali ...

  9. Spark streaming消费Kafka的正确姿势

    前言 在游戏项目中,需要对每天千万级的游戏评论信息进行词频统计,在生产者一端,我们将数据按照每天的拉取时间存入了Kafka当中,而在消费者一端,我们利用了spark streaming从kafka中不 ...

随机推荐

  1. [转]linux之ps命令

    转自:http://www.cnblogs.com/peida/archive/2012/12/19/2824418.html Linux中的ps命令是Process Status的缩写.ps命令用来 ...

  2. InnoDB锁机制之Gap Lock、Next-Key Lock、Record Lock解析

    InnoDB锁机制之Gap Lock.Next-Key Lock.Record Lock解析 有意思,解释的很好

  3. iOS动画——DynamicAnimate

    力学动画 以dynamicAnimate为首的力学动画是苹果在iOS7加入的API,里面包含了很多力学行为,这套API是基于Box2d实现的.其中包含了重力.碰撞.推.甩.和自定义行为. 涉及到的类如 ...

  4. OFDM同步算法之Park算法

    park算法代码 训练序列结构 T=[\(C\) \(D\) \(C^{*}\) \(D^{*}\)],其中C表示由长度为N/4的复伪随机序列PN,ifft变换得到的符号序列 \(C(n) = D(N ...

  5. StackOverflowError&OutOfMemoryError区别

    在Java虚拟机规范中,针对内存分配规定两种异常状况,即StackOverflowError和OutOfMemoryError. StackOverflowError:当线程请求的内存大小大于所配置的 ...

  6. Android Thermal-engine

    Thermal Engine Thermal 相关的东西主要在Vendor/qcom/proprietary/thermal-engine 目录下: thermal-engine.conf 文件可以用 ...

  7. html5——DOM扩展

    元素获取 1.document.getElementsByClassName ('class') 通过类名获取元素,以类数组形式存在. 2.document.querySelector(‘div’) ...

  8. CSS——半透明

    1.opacity:不仅背景半透明,内部其他元素也半透明 2.rgba():只有背景半透明. <!DOCTYPE html> <html lang="en"> ...

  9. js分页插件

    //分页插件1function showView(option) {    //参数定义id,页容量,当前页,总数,页总数    var id = option.id,         pageSiz ...

  10. 小程序 之picker-view省市县

    代码地址:https://github.com/yangsphp/area-picker