SparkSql與Redis綜合練習

鴨梨山大哎發表於2020-12-08

資料

A0001	202.106.196.115	手機	iphone8	8000
A0002	202.106.196.116	服裝	Tshirt	450
A0003	202.106.196.117	藥品	阿莫西林	40
A0004	202.106.196.118	藥品	板藍根	23
A0005	202.106.196.119	手機	iphone9	8000
A0006	202.106.196.120	服裝	Tshirt	320
A0007	202.106.196.121	藥品	阿莫西林	40
A0008	202.106.196.122	藥品	板藍根	23
A0009	202.106.196.123	手機	iphone10	8000
A0010	202.106.196.124	服裝	Tshirt	450
A0011	202.106.196.125	藥品	阿莫西林	40
A0012	202.106.196.126	藥品	板藍根	23
A0013	202.106.196.127	手機	iphone11	8000
A0014	202.106.196.128	服裝	Tshirt	450
A0015	202.106.196.129	藥品	阿莫西林	40
A0016	202.106.196.130	藥品	板藍根	23
A0017	202.106.196.131	手機	iphone12	9999
A0018	202.106.196.132	服裝	Tshirt	340

需求

問題1.計算出總的成交量總額(結果儲存到redis中)
問題2.計算每個商品分類的成交量(結果儲存到redis中)
問題3.計算每個省份的成交總額(結果儲存到redis)

scala程式碼

package com.hm.spark.day03

import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import redis.clients.jedis.{Jedis, JedisPool}

/**
 * 問題1.計算出總的成交量總額(結果儲存到redis中)
 * 問題2.計算每個商品分類的成交量(結果儲存到redis中)
 * 問題3.計算每個省份的成交總額(結果儲存到redis)
 */
object HomeWork1 extends App {
  private val spark: SparkSession = SparkSession.builder().master("local[2]").appName("test")
    .getOrCreate()
  private val df: DataFrame = spark.read.csv("D://tmp/test.csv").toDF("id", "ip", "kind", "detail", "price")
  df.show()
  df.createTempView("tmp")
  //totalTurnOver(df)
  getPerTurnOver(df)


  //問題1.計算出總的成交量總額(結果儲存到redis中)
  def totalTurnOver(df:DataFrame): Unit ={
    val sql =
      """
        |select sum(price) total
        |from
        |tmp
        |""".stripMargin
     val result: DataFrame = spark.sql(sql)
     val rows: Array[Row] = result.take(1)
    println(rows.mkString("Array(", ", ", ")"))
     val total: Double = rows(0).getDouble(0)
    SaveSumToRedis(total)
  }
  //問題2.計算每個商品分類的成交量(結果儲存到redis中)
 def getPerTurnOver(df:DataFrame): Unit ={
   val sql =
     """
       |select kind,sum(price) total
       |from
       |tmp
       |group by kind
       |""".stripMargin
   val result: DataFrame = spark.sql(sql)
   val rows1: Array[Row] = result.collect()
   val jedis: Jedis = getJedis
   for(x<-rows1){
     val kind: String = x.getString(0)
     val price: Double = x.getDouble(1)
     jedis.hset("sales",kind,price.toString)
   }
 }

  def getJedis: Jedis = {
    val config = new GenericObjectPoolConfig()
    val pool = new JedisPool(config, "mypc01", 6379)
    val jedis: Jedis = pool.getResource
    jedis
  }

  def SaveSumToRedis(num: Double): Unit = {
    val jedis: Jedis = getJedis
    jedis.hset("sales", "totalprice", num.toString)
  }
}


相關文章