structStreaming 实例二从Kafka 中读取数据保存到mysql中

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spark01</artifactId>
    <version>1.0-SNAPSHOT</version>


    <!-- 指定仓库位置,依次为aliyun、cloudera和jboss仓库 -->
    <repositories>
        <repository>
            <id>aliyun</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
        </repository>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/nexus/content/groups/public</url>
        </repository>

        <repository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </pluginRepository>
    </pluginRepositories>


    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <encoding>UTF-8</encoding>
        <scala.version>2.11.8</scala.version>
        <scala.compat.version>2.11</scala.compat.version>
        <hadoop.version>2.7.4</hadoop.version>
        <spark.version>2.2.0</spark.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-hive_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-hive-thriftserver_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>
        <!-- <dependency>
             <groupId>org.apache.spark</groupId>
             <artifactId>spark-streaming-kafka-0-8_2.11</artifactId>
             <version>${spark.version}</version>
         </dependency>-->
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql-kafka-0-10_2.11</artifactId>
            <version>${spark.version}</version>
        </dependency>

        <!--<dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.6.0-mr1-cdh5.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>1.2.0-cdh5.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>1.2.0-cdh5.14.0</version>
        </dependency>-->

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.7.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src/main/scala</sourceDirectory>
        <testSourceDirectory>src/test/scala</testSourceDirectory>
        <plugins>
            <!-- 指定编译java的插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
            </plugin>
            <!-- 指定编译scala的插件 -->
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>3.2.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                        <configuration>
                            <args>
                                <arg>-dependencyfile</arg>
                                <arg>${project.build.directory}/.scala_dependencies</arg>
                            </args>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <useFile>false</useFile>
                    <disableXmlReport>true</disableXmlReport>
                    <includes>
                        <include>**/*Test.*</include>
                        <include>**/*Suite.*</include>
                    </includes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass></mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

主类

import org.apache.spark.sql.{Dataset, SparkSession}

/**
 * @author 红尘丶世界
 * @version v 1.0
 *       structStreaming 集成kafka -> 集成mysql
 */
object StructStreamingKafkaOutMysql {
  def main(args: Array[String]): Unit = {
    //1.准备环境
    // 创建sparkSession
    val spark: SparkSession = SparkSession.builder()
      .appName("structStreamingMysql")
      .master("local[*]")
      .getOrCreate()
    spark.sparkContext.setLogLevel("ERROR")

    //2.接收数据
    val kafkaData = spark.readStream.format("kafka")
      .option("kafka.bootstrap.servers", "hadoop01:9092,hadoop02:9092,hadoop03:9092") //指定节点
      .option("subscribe", "test03") //指定topic
      .load()

    //3.计算数据
    import spark.implicits._
    val kafkaDataString: Dataset[(String, String)] = kafkaData.selectExpr("CAST(key AS string)", "CAST(value AS string)").as[(String, String)]
    val word: Dataset[String] = kafkaDataString.flatMap(a => a._2.split(" "))
    val wordCount = word.groupBy("value").count().sort($"count".desc)

    val intoMysql = new OutputToMySql("jdbc:mysql://hadoop01:3306/spark_streaming?characterEncoding=UTF-8", "root", "123456")

    //4.输出数据
    wordCount.writeStream
      .foreach(intoMysql)
      .outputMode("complete")
      .start()
      .awaitTermination()
  }
}

保存数据

import java.sql.{Connection, DriverManager, PreparedStatement}

import org.apache.spark.sql.{ForeachWriter, Row}

/**
 * @author 红尘丶世界
 * @version v 1.0
 */
class OutputToMySql(url: String, username: String, password: String) extends ForeachWriter[Row] with Serializable {
  var connection: Connection = _
  var ps: PreparedStatement = _


  //5.打开数据库连接
  override def open(partitionId: Long, version: Long): Boolean = {
    connection = DriverManager.getConnection(url, username, password)
    true
  }

  //6.将数据写入/更新到mysql
  override def process(value: Row): Unit = {
    //value 内的第一个数据是单词,第二个是单词的数量
    //获取到数据
    val word: String = value.get(0).toString
    val count: Int = value.get(1).toString.toInt
    println(s"word = ${word}\tcount = ${count}")
//    val sql = "INSERT INTO t_word (id, word, count) VALUES (null,?,?) ON DUPLICATE KEY UPDATE count = ?"
    val sql ="replace into t_word (id, word, count) VALUES (null,?,?)"
    ps = connection.prepareStatement(sql)
    //设置 word 的值
    ps.setString(1, word)
    //设置 count 的值
    ps.setInt(2, count)
//    ps.setInt(3, count)
    ps.executeUpdate()
  }

  //7.关闭连接
  override def close(errorOrNull: Throwable): Unit = {
    if (ps != null) {
      ps.close()
    }
    if (connection != null){
      connection.close()
    }
  }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题的意思是如何使用b'sparkstreaming\xe3\x80\x8a\xe4\xb8\x89\xe3\x80\x8b'来读取Kafka数据,并将增量存储在MySQL。 首先需要使用Spark StreamingKafka Direct API来读取Kafka数据,然后将获得的数据转换为DataFrame或RDD。接下来将增量数据存储到MySQL,可以使用Spark SQL或Dataframe APIs来实现。代码示例如下: ``` from pyspark.sql import SparkSession from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from pyspark.sql.functions import * # 创建SparkSession spark = SparkSession.builder.appName("KafkaToMySQL").getOrCreate() # 创建StreamingContext ssc = StreamingContext(spark.sparkContext, batchDuration=5) # 设置Kafka参数 kafkaParams = {"bootstrap.servers": "localhost:9092", "group.id": "testGroup"} # 创建Kafka direct stream kafkaStream = KafkaUtils.createDirectStream(ssc, topics=["testTopic"], kafkaParams=kafkaParams) # 处理Kafka数据,并保存MySQL def processBatch(batchTime, rdd): if not rdd.isEmpty(): # 转换为DataFrame df = spark.read.json(rdd) # 将时间戳转换为日期 df = df.withColumn("date", from_unixtime(col("timestamp"), "yyyy-MM-dd")) # 计算增量 incremental_data = df.groupBy("date").agg(sum("value").alias("incremental_value")) # 将增量数据写入MySQL incremental_data.write.format("jdbc").option("url", "jdbc:mysql://localhost/test").option("dbtable", "incremental_data").option("user", "root").option("password", "root").mode("append").save() # 处理每个批次 kafkaStream.foreachRDD(processBatch) # 启动StreamingContext ssc.start() ssc.awaitTermination() ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值