SparkStreaming读取Kafka数据

package kafka

import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.{Duration, StreamingContext}
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
/*记得添加依赖
<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
  <version>2.2.0</version>
</dependency>*/

object KafkaSparkStreaming {
  val conf=new SparkConf().setMaster("local[*]").setAppName("data from kafka")
  val ssc=new StreamingContext(conf,Duration(5))

  def main(args: Array[String]): Unit = {
    //kafka的配置参数
    val kafkaParams = Map(
      "bootstrap.servers" -> "master:9092,master:9093",
      ("key.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer"),
      "value.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
      "group.id" -> "kafkaTest",
      "enable.auto.commit" -> "false"
    )

    val topics = Set("spark")//创建topic
    val kafkaDstream = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,//本地策略
      Subscribe[String, String](topics, kafkaParams)//消费策略
    ).map(x=>x.value())
      .flatMap(_.split("\\s"))
      .map((_,1))
      .reduceByKey(_+_)
      .print()
    
    ssc.start()
    ssc.awaitTermination()
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值