kafka+Structured Streaming+s3+dynamodb

本文介绍了一个使用Spark Streaming从Kafka消费数据并进行实时处理的示例,包括统计页面访问量(PV)和独立访客数(UV),最终将处理结果输出到DynamoDB和S3。

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

本文主要介绍从kafka消费数据,并通过两个业务需求(统计PV,UV),然后分别输出到dynamodb和S3的demo,demo仅做演示逻辑,无法直接使用

def main(args: Array[String]) {
    val bucket:String = _
    val pvCheckLocation:String = _
    val uvCheckLocation:String = _
    val uvPath:String = _
    //create spark session
    val spark = SparkSession.builder()
      .master("local[*]")
      .config("spark.eventLog.enabled", "false")
      .config("spark.driver.memory", "2g")
      .config("spark.executor.memory", "2g")
      .config("spark.sql.shuffle.partitions","4")
      .appName("kafkaDemoToS3AndDynamoDB")
      .getOrCreate()
    import spark.implicits._
    //read stream from kafka
    val kafkaStream = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
      .option("subscribe", "topic1,topic2")
      .option("startingOffsets", "latest")
      .option("failOnDataLoss", false)
      .option("maxOffsetsPerTrigger", 10L)
      .load()
      .selectExpr("CAST(value AS STRING)",
        "CAST(topic as STRING)",
        "CAST(partition as INTEGER)")
      .as[(String, String, Integer)]
    val cols = List("domain", "ip", "timestamp")
    //parse data to entity
    val df = kafkaStream.map { line =>
    val columns = line._1.split(" ")
      (columns(0), columns(1), columns(2))
    }.toDF(cols:_*)

    //all logs
    val ds = df.distinct().select($"domain", $"ip", $"timestamp").as[ClickStream]

    //compute pv
    val dsPV = ds.map(x => (x.domain,(x.ip,x.timestamp))).groupBy(x.domain)....count()
    //compute uv
    val dsUV = ds.map(x => (x.domain,x.ip)).groupBy(x.domain).....count()

    //save pv to dynamodb
    val queryPVCount = dsPV.writeStream
      .outputMode("update")
      .trigger(Trigger.ProcessingTime("10 seconds"))
      .option("checkpointLocation", pvCheckLocation)
      .foreach(new ForeachWriter[Row] {
      var ddbClient: AmazonDynamoDBClient = _

      override def open(partitionId: Long, version: Long) = {
        ddbClient = new dynamodbv2.AmazonDynamoDBClient()
        true
      }

      override def process(value: Row) = {
        val put = new PutItemRequest()
        put.setTableName("table")
        var attr = new AttributeValue()
        attr.setS(value.getAs[String](0))
        put.addItemEntry("domain", attr)
        attr = new AttributeValue()
        attr.setN(value.getAs[Long](1).toString)
        put.addItemEntry("pv", attr)
        ddbClient.putItem(put)
      }

      override def close(errorOrNull: Throwable) = {
      }
    }
    ).start()

    //save uv to s3
    val queryUVCount = dsUV.writeStream
      .outputMode("update")
      .trigger(Trigger.ProcessingTime("10 seconds"))
      .option("checkpointLocation", uvCheckLocation)
      .start("s3://" + bucket+ "/" +  uvPath)

    queryPVCount.awaitTermination()
    queryUVCount.awaitTermination()
  }
  //entity
  case class ClickStream(domain:String, ip:String,timestamp:Long)




### Spring Boot 整合 Flume, KafkaSpark Streaming 架构设计 #### 1. 数据流概述 在该架构中,Flume 被用于收集来自不同源头的日志数据并将其传输到 Kafka 中。Kafka 则作为一个高吞吐量的消息队列来存储这些日志消息直到被处理。而 Spark Streaming 扮演着消费者的角色,它会订阅特定主题下的消息来进行实时分析工作[^1]。 #### 2. 组件间交互流程描述 - **Flume Agent**: 配置好 source、channel 及 sink 后启动 agent 实例;source 接收应用程序产生的原始日志文件或其他形式输入的数据,并通过 channel 发送到指定位置即 Kafkatopic 上。 - **Kafka Broker**: 创建相应的 topics 来接收由 flume 发送过来的信息片段,在此期间可以设置副本因子以及分区数量以提高系统的可靠性和性能表现[^5]。 - **Spring Boot Application with Embedded Consumer Logic**: - 使用 `@KafkaListener` 注解监听目标 Topic 并消费其中的内容; - 对获取到的消息执行初步过滤或转换操作以便后续传递给 spark streaming 进行更深入地加工处理。 - **Spark Streaming Job Submission via REST API Provided by Spring Boot App** - 开发者可以在 spring boot 应用程序内部定义一套 restful api ,允许外部调用来提交新的 spark job 或管理现有作业的状态 (start/stop/retrieve logs etc.) ; - 当收到请求时,则按照预设参数构建命令字符串并通过 ProcessBuilder 类型对象去运行实际的 shell 命令完成任务部署过程[^3]。 ```bash # Example of submitting a Spark Streaming application through command line which could be invoked programmatically within the Spring Boot app. ./spark-submit \ --class com.example.SparkJobClass \ --master yarn-client \ --num-executors 4 \ --executor-memory 2G \ --total-executor-cores 8 \ /path/to/application-jar-file.jar \ <args> ``` #### 3. 技术选型考量因素 为了确保整个体系结构具备良好的扩展能力与维护便利性,在技术栈的选择方面需综合考虑如下几个维度: - **兼容性**:所选用的技术组件之间是否存在良好协作关系?比如版本匹配度如何? - **社区支持程度**:是否有活跃开发者群体提供帮助文档和技术指导资源? - **成本效益比**:硬件设施投入产出比例是否合理? ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值