簡單的Spark+Mysql整合開發

    今天簡單說下Spark和Mysql的整合開發,首先要知道:在Spark中提供了一個JdbcRDD類,該RDD就是讀取JDBC中的數據並轉換成RDD,以後咱們就能夠對該RDD進行各類的操做,該類的構造函數以下:java

JdbcRDD[T: ClassTag](
    sc: SparkContext,
    getConnection: () => Connection,
    sql: String,
    lowerBound: Long,
    upperBound: Long,
    numPartitions: Int,
    mapRow: (ResultSet) => T = JdbcRDD.resultSetToObjectArray _)

    參數:mysql

    (1)getConnection 返回一個已經打開的結構化數據庫鏈接,JdbcRDD會自動維護關閉。
 (2)sql 是查詢語句,此查詢語句必須包含兩處佔位符?來做爲分割數據庫ResulSet的參數,例如:"select title, author from books where ? < = id and id <= ?"
 (3)lowerBound, upperBound, numPartitions 分別爲第1、第二佔位符,partition的個數。例如,給出lowebound 1,upperbound 20, numpartitions 2,則查詢分別爲(1, 10)與(11, 20)
 (4)mapRow 是轉換函數,將返回的ResultSet轉成RDD需用的單行數據,此處能夠選擇Array或其餘,也能夠是自定義的case class。默認的是將ResultSet 轉換成一個Object數組。web

    下面是動手實踐,個人開發環境是:sql

    虛擬機CentOs7系統,IDEA,JDK8,Scala 2.11,Spark 2.0.1,一些基本環境問題這裏就再也不敘述了。數據庫

    本人使用的是maven,建立maven項目,初始化並添加依賴,下面是pom.xml:apache

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JdbcRdd</groupId>
  <artifactId>Demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <inceptionYear>2018</inceptionYear>
  <properties>
    <scala.version>2.11.8</scala.version>
  </properties>

  <repositories>
    <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>

  <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>2.0.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.25</version>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
          <args>
            <arg>-target:jvm-1.5</arg>
          </args>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>
          <downloadSources>true</downloadSources>
          <buildcommands>
            <buildcommand>ch.epfl.lamp.sdt.core.scalabuilder</buildcommand>
          </buildcommands>
          <additionalProjectnatures>
            <projectnature>ch.epfl.lamp.sdt.core.scalanature</projectnature>
          </additionalProjectnatures>
          <classpathContainers>
            <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
            <classpathContainer>ch.epfl.lamp.sdt.launching.SCALA_CONTAINER</classpathContainer>
          </classpathContainers>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>

    新建scala的Object類,以下:數組

package JdbcRdd

import java.sql.DriverManager

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.JdbcRDD

object SparkToJdbc {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("mysql").setMaster("local")
    val sc = new SparkContext(conf)
    val rdd = new JdbcRDD(
      sc,()=>{
        Class.forName("com.mysql.jdbc.Driver").newInstance()
        DriverManager.getConnection("jdbc:mysql://鏈接的IP:3306/鏈接的數據庫名", "用戶名", "密碼")
      },
      "SELECT CATEGORY FROM nyw_knowledges WHERE COMPANY_CODE >= ? AND COMPANY_CODE <= ?",
      1000, 1200, 3,
      r => r.getString(1)).cache()

    val rd = rdd.filter(_.contains("諮詢")).count()
    println(rd)

    sc.stop()
  }
}

    這裏基本的代碼就這些,鏈接數據庫後對錶進行操做。eclipse

    注意:這裏可能會出現幾個問題,須要慎重處理:jvm

    (1)內存問題:若是內存不夠,則須要從新設置,本人使用的是運行時配置:maven

    也能夠用另外一種方式,在代碼中配置,

    可參考:http://blog.csdn.net/qingyang0320/article/details/50787550

    (2)數據庫訪問限制問題

    報錯:java.sql.SQLException: null, message from server: 「Host ‘xxx’ is not allowed to connect,該問題是因爲本機的訪問權限未開放,須要進行設置。

    可參考:http://blog.csdn.net/xionglangs/article/details/50385057

    (3)mysql Driver依賴未添加報錯

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.25</version>
</dependency>

    結果:

    經過訪問Spark web UI的地址:localhost:4040可以清楚的查看具體的spark參數,大功告成。

相關文章
相關標籤/搜索