广播的目的
广播变量是为了实现mapside join ,可以将Driver端的数据广播到属于该application的Executor,然后通过Driver广播变量返回的引用,获取事先广播到Executor的数据。
mapside join
当连接的两个表是一个比较大的表和一个比较小的时候,我们把比较小的table直接放到内存中去,然后再去对比较大的表格进行map操作。join就发生在map操作的时候,每当扫描一个大的table中的数据,就要去查看小表的数据,哪条与之相符,继而进行连接,这里的join并不会涉及reduce操作,map端join的优势就是在于没有shuffle。
案例:根据IP计算归属地
需求:根据IP规则数据,计算出给定日志中IP地址对应的省份信息。
import scala.collection.mutable.ArrayBuffer
/**
* @author:mcf
* @Date:2020/9/26 16:13
* @Description:
*/
object IPUtils {
//将IP地址转成十进制
def ip2Long(ip:String):Long ={
val fragements = ip.split("[.]")
var ipNum = 0L
for (i <- 0 until fragements.length){
ipNum = fragements(i).toLong | ipNum << 8L
}
ipNum
}
//二分查找
def binarySearch(lines:ArrayBuffer[(Long,Long,String,String )],ip:Long):Int ={
var low = 0 //起始
var high = lines.length - 1 //结束
while(low <= high){
val middle = (low + high) /2
if ((ip >= lines(middle)._1) && (ip <= lines(middle)._2))
return middle
if (ip < lines(middle)._1)
high = middle - 1
else {
low = middle + 1
}
}
-1 //没有找到
}
def binarySearch(lines: Array[(Long, Long, String, String)], ip: Long): Int = {
var low = 0 //起始
var high = lines.length - 1 //结束
while (low <= high) {
val middle = (low + high) / 2
if ((ip >= lines(middle)._1) && (ip <= lines(middle)._2))
return middle
if (ip < lines(middle)._1)
high = middle - 1
else {
low = middle + 1
}
}
-1 //没有找到
}
}
/**
* @author:mcf
* @Date:2020/9/26 16:13
* @Description:
*/
object IPDemo {
def main(args: Array[String]): Unit = {
val isLocal = args(0).toBoolean
val conf = new SparkConf().setAppName(this.getClass.getSimpleName)
if (isLocal){
conf.setMaster("local[*]")
}
val sc = new SparkContext(conf)
//先读取IP规则数据
val ipLines: RDD[String] = sc.textFile(args(1))
val ipRulesInDriver: Array[(Long, Long, String, String)] = ipLines.map(line => {
val fields: Array[String] = line.split("[|]")
val startNum: Long = fields(2).toLong
val endNum: Long = fields(3).toLong
val province: String = fields(6)
val city: String = fields(7)
(startNum, endNum, province, city)
}).sortBy(_._1) //按照IP地址的起始十进制排序(因为以后用二分法查找)
.collect()//将全部的IP规则收集到Driver
//将Driver端全部的IP规则数据广播到属于该Application的Executor
//broadcast 方法是一个同步的方法,如果没有广播完,Driver端的代码是阻塞的
val broadcastRefInDriver: Broadcast[Array[(Long, Long, String, String)]] = sc.broadcast(ipRulesInDriver)
//读访问日志的数据
val accessLines: RDD[String] = sc.textFile(args(2))
//对数据进行切分整理
val reduced: RDD[(String, Int)] = accessLines.map(line => {
val fields: Array[String] = line.split("[|]")
val ip: String = fields(1)
val ipNum: Long = IPUtils.ip2Long(ip)
//关联Executor中事先已经广播好的数据
val ipRulesInExecutor: Array[(Long, Long, String, String)] = broadcastRefInDriver.value
//在Executor中,通过广播变量的引用,获取事先已经广播好的数据
val index: Int = IPUtils.binarySearch(ipRulesInExecutor, ipNum)
var province = "未知"
if (index > -1) {
province = ipRulesInExecutor(index)._3
}
(province, 1)
}).reduceByKey(_ + _)
val res = reduced.collect()
println(res.toBuffer)
sc.stop()
}
}
ArrayBuffer((陕西,1824), (河北,383), (云南,126), (未知,1), (重庆,868), (北京,1535))