spark streaming - kafka updateStateByKey 统计用户消费金额

本文介绍如何使用Spark Streaming结合Kafka处理实时用户消费数据,通过updateStateByKey实现每分钟及累计消费额统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景

餐厅老板想要统计每个用户来他的店里总共消费了多少金额,我们可以使用updateStateByKey来实现

从kafka接收用户消费json数据,统计每分钟用户的消费情况,并且统计所有时间所有用户的消费情况(使用updateStateByKey来实现)

数据格式

{"user":"zhangsan","payment":8}
{"user":"wangwu","payment":7}
....

往kafka写入消息(kafka producer)

package producer

import java.util.Properties

import kafka.javaapi.producer.Producer
import kafka.producer.{KeyedMessage, ProducerConfig}
import org.codehaus.jettison.json.JSONObject
import scala.util.Random

object KafkaProducer extends App{

  //所有用户
  private val users = Array(
    "zhangsan", "lisi",
    "wangwu", "zhaoliu")

  private val random = new Random()

  //消费的金额(0-9)
  def payMount() : Double = {
    random.nextInt(10)
  }

  //随机获得用户名称
  def getUserName() : String = {
    users(random.nextInt(users.length))
  }

  //kafka参数
  val topic = "user_payment"
  val brokers = "192.168.6.55:9092,192.168.6.56:9092"
  val props = new Properties()
  props.put("metadata.broker.list", brokers)
  props.put("serializer.class", "kafka.serializer.StringEncoder")

  val kafkaConfig = new ProducerConfig(props)
  val producer = new Producer[String, String](kafkaConfig)

  while(true) {
    // 创建json串
    val event = new JSONObject()
    event
      .put("user", getUserName())
      .put("payment", payMount)

    // 往kafka发送数据
    producer.send(new KeyedMessage[String, String](topic, event.toString))
    println("Message sent: " + event)

    //每隔200ms发送一条数据
    Thread.sleep(200)
  }
}

使用spark Streaming处理数据

import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.streaming.{StreamingContext, Seconds}
import org.apache.spark.{SparkContext, SparkConf}
import net.liftweb.json._

object UpdateStateByKeyTest {

  def main (args: Array[String]) {

    def functionToCreateContext(): StreamingContext = {
    //创建streamingContext
      val conf = new SparkConf().setAppName("test").setMaster("local[*]")
      val ssc = new StreamingContext(conf, Seconds(60))

      //将数据进行保存(这里作为演示,生产中保存在hdfs)
      ssc.checkpoint("checkPoint")

      val zkQuorum = "192.168.6.55:2181,192.168.6.56:2181,192.168.6.57:2181"
      val consumerGroupName = "user_payment"
      val kafkaTopic = "user_payment"
      val kafkaThreadNum = 1

      val topicMap = kafkaTopic.split(",").map((_, kafkaThreadNum.toInt)).toMap

    //从kafka读入数据并且将json串进行解析
      val user_payment = KafkaUtils.createStream(ssc, zkQuorum, consumerGroupName, topicMap).map(x=>{
        parse(x._2)
      })

     //对一分钟的数据进行计算
      val paymentSum = user_payment.map(jsonLine =>{
        implicit val formats = DefaultFormats
        val user = (jsonLine \ "user").extract[String]
        val payment = (jsonLine \ "payment").extract[String]
        (user,payment.toDouble)
      }).reduceByKey(_+_)

      //输出每分钟的计算结果
      paymentSum.print()

    //将以前的数据和最新一分钟的数据进行求和
      val addFunction = (currValues : Seq[Double],preVauleState : Option[Double]) => {
        val currentSum = currValues.sum
        val previousSum = preVauleState.getOrElse(0.0)
        Some(currentSum + previousSum)
      }

      val totalPayment = paymentSum.updateStateByKey[Double](addFunction)

      //输出总计的结果
      totalPayment.print()

      ssc
    }

    //如果"checkPoint"中存在以前的记录,则重启streamingContext,读取以前保存的数据,否则创建新的StreamingContext
    val context = StreamingContext.getOrCreate("checkPoint", functionToCreateContext _)

    context.start()
    context.awaitTermination()
  }
}

运行结果节选

//-----------第n分钟的结果------------------

//1分钟结果
-------------------
(zhangsan,23.0)
(lisi,37.0)
(wangwu,31.0)
(zhaoliu,34.0)
-------------------

//总和结果 
(zhangsan,101.0)
(lisi,83.0)
(wangwu,80.0)
(zhaoliu,130.0)

//-----------第n+1分钟的结果------------------

//1分钟结果
-------------------
(zhangsan,43.0)
(lisi,16.0)
(wangwu,21.0)
(zhaoliu,54.0)
-------------------
//总和结果 
-------------------
(zhangsan,144.0)
(lisi,99.0)
(wangwu,101.0)
(zhaoliu,184.0)
-------------------

后记

下一片文章为统计不同时间段用户平均消费金额,消费次数,消费总额等指标。
点击这里

### 使用 Spark Streaming 实现词频统计 为了实现基于 Spark Streaming 的词频统计功能,可以按照如下方法构建应用程序。此应用会读取来自某个源的数据流并计算其中单词出现的频率。 #### 创建案例类用于转换 RDD 到 DataFrame 定义 `Record` 类来表示每条记录中的单个词语: ```scala /** Case class for converting RDD to DataFrame */ case class Record(word: String) ``` #### 单例模式下的 SparkSession 获取 采用懒加载的方式获取唯一的 `SparkSession` 实例,确保在整个应用程序生命周期内只有一个 `SparkSession` 被创建和使用: ```scala object SparkSessionSingleton { @transient private var instance: SparkSession = _ def getInstance(sparkConf: SparkConf): SparkSession = { if (instance == null) { instance = SparkSession.builder.config(sparkConf).getOrCreate() } instance } } ``` #### 构建 Spark 流程逻辑 下面展示了一个完整的流程框架,它接收输入 DStream 并执行词频统计操作: ```scala val conf = new SparkConf().setAppName("WordCountApp").setMaster("local[*]") // Create a local StreamingContext with two working threads and batch interval of 1 second. val ssc = new StreamingContext(conf, Seconds(1)) // Define the checkpoint directory which is required for stateful transformations like updateStateByKey or window operations. ssc.checkpoint("/path/to/checkpoint") // Source can be any input source such as Kafka, Flume etc., here we assume textFileStream as an example. val lines = ssc.textFileStream("/path/to/input") // Input path where files will appear. // Split each line into words val words = lines.flatMap(_.split(" ")) // Map each word to a tuple containing the word and count of one val pairs = words.map(word => (word, 1)) // Count occurrences of each word over all batches using updateStateByKey function that maintains running totals across multiple batches. var wordCounts = pairs.updateStateByKey[Int](updateFunc) // Print out top ten most frequent words every few seconds. wordCounts.print() ssc.start() // Start the computation ssc.awaitTermination() // Wait for the computation to terminate ``` 上述代码片段展示了如何设置 Spark 配置以及初始化 Streaming 上下文环境;指定了批处理间隔时间,并设置了检查路径以便支持状态化转换操作[^3]。 对于更新函数 `updateFunc` 可以这样定义: ```scala def updateFunc(values: Seq[Int], state: State[Int]): Option[(String, Int)] = { val currentCount = values.sum + state.getOption.getOrElse(0) Some((state.key.toString(), currentCount)) } ``` 这段代码实现了当接收到新的键值对时,将新旧计数值相加得到最新的总次数,并返回包含该单词及其最新累计数量的结果元组。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值