基本用法主要掌握一点就行:

master slave模式运用:driver 就是master,executor就是slave。

如果executor要想和driver交互必须拿到driver的EndpointRef,通过driver的EndpointRef来调接口访问。

driver启动时,会在driver中注册一个Endpoint服务,并暴露自己的ip和端口。executor端生成driver的EndpointRef,就主要需要两个参数就行:driver的host(ip)和port。

导入Maven依赖

        <dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.4.0</version>
</dependency>

定义RPC Server端的ip(localhost)。port(57992)、服务名称(hello-rpc-service)

object HelloRpcSettings {
val rpcName = "hello-rpc-service"
val port = 57992
val hostname="localhost" def getName() = {
rpcName
} def getPort(): Int = {
port
} def getHostname():String={
hostname
}
}

定义RPC的Endpoint类和发送数据类SayHi/SayBye

case class SayHi(msg: String)

case class SayBye(msg: String)

import org.apache.spark.rpc.{RpcCallContext, RpcEndpoint, RpcEnv}

class HelloEndpoint(override val rpcEnv: RpcEnv) extends RpcEndpoint {
override def onStart(): Unit = {
println(rpcEnv.address)
println("start hello endpoint")
} override def receive: PartialFunction[Any, Unit] = {
case SayHi(msg) =>
println(s"receive $msg" )
} override def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {
case SayHi(msg) => {
println(s"receive $msg")
context.reply(s"hi, $msg")
}
case SayBye(msg) => {
println(s"receive $msg")
context.reply(s"bye, $msg")
}
} override def onStop(): Unit = {
println("stop hello endpoint")
}
}

定义RPC 服务提供者

import org.apache.spark.{SecurityManager, SparkConf, SparkContext, SparkEnv}
import org.apache.spark.rpc._
import org.apache.spark.sql.SparkSession object RpcServerTest {
def main(args: Array[String]): Unit = {
val conf: SparkConf = new SparkConf()
val sparkSession = SparkSession.builder().config(conf).master("local[*]").appName("test rpc").getOrCreate()
val sparkContext: SparkContext = sparkSession.sparkContext
val sparkEnv: SparkEnv = sparkContext.env val rpcEnv = RpcEnv.create(HelloRpcSettings.getName(), HelloRpcSettings.getHostname(), HelloRpcSettings.getHostname(), HelloRpcSettings.getPort(), conf,
sparkEnv.securityManager, 1, false) val helloEndpoint: RpcEndpoint = new HelloEndpoint(rpcEnv)
rpcEnv.setupEndpoint(HelloRpcSettings.getName(), helloEndpoint) rpcEnv.awaitTermination()
}
}

定义RPC服务使用者

import org.apache.spark.{SecurityManager, SparkConf, SparkContext, SparkEnv}
import org.apache.spark.rpc.{RpcAddress, RpcEndpointRef, RpcEnv, RpcEnvConfig}
import org.apache.spark.sql.{Dataset, Row, SparkSession} import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future} object RpcClientTest {
def main(args: Array[String]): Unit = {
val conf: SparkConf = new SparkConf()
val sparkSession = SparkSession.builder().config(conf).master("local[*]").appName("test rpc").getOrCreate()
val sparkContext: SparkContext = sparkSession.sparkContext
val sparkEnv: SparkEnv = sparkContext.env val rpcEnv: RpcEnv = RpcEnv.create(HelloRpcSettings.getName(),HelloRpcSettings.getHostname(),HelloRpcSettings.getPort(),conf,sparkEnv.securityManager,false)
val endPointRef: RpcEndpointRef = rpcEnv.setupEndpointRef(RpcAddress(HelloRpcSettings.getHostname(), HelloRpcSettings.getPort()), HelloRpcSettings.getName()) import scala.concurrent.ExecutionContext.Implicits.global endPointRef.send(SayHi("test send")) val future: Future[String] = endPointRef.ask[String](SayHi("neo"))
future.onComplete {
case scala.util.Success(value) => println(s"Got the result = $value")
case scala.util.Failure(e) => println(s"Got error: $e")
}
Await.result(future, Duration.apply("30s")) val res = endPointRef.askSync[String](SayBye("test askSync"))
println(res) sparkSession.stop()
} }

启动RPC 服务提供者

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
// :: INFO SparkContext: Running Spark version 2.4.
// :: WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
// :: INFO SparkContext: Submitted application: test rpc
// :: INFO SecurityManager: Changing view acls to: boco
// :: INFO SecurityManager: Changing modify acls to: boco
// :: INFO SecurityManager: Changing view acls groups to:
// :: INFO SecurityManager: Changing modify acls groups to:
// :: INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(boco); groups with view permissions: Set(); users with modify permissions: Set(boco); groups with modify permissions: Set()
// :: INFO Utils: Successfully started service 'sparkDriver' on port .
// :: INFO SparkEnv: Registering MapOutputTracker
// :: INFO SparkEnv: Registering BlockManagerMaster
// :: INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
// :: INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
// :: INFO DiskBlockManager: Created local directory at C:\Users\boco\AppData\Local\Temp\blockmgr-7128dde8-9c46--bb72-c2161ba65bf7
// :: INFO MemoryStore: MemoryStore started with capacity 901.8 MB
// :: INFO SparkEnv: Registering OutputCommitCoordinator
// :: INFO Utils: Successfully started service 'SparkUI' on port .
// :: INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://DESKTOP-JL4FSCV:4040
// :: INFO Executor: Starting executor ID driver on host localhost
// :: INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port .
// :: INFO NettyBlockTransferService: Server created on DESKTOP-JL4FSCV:
// :: INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
// :: INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: INFO BlockManagerMasterEndpoint: Registering block manager DESKTOP-JL4FSCV: with 901.8 MB RAM, BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: INFO Utils: Successfully started service 'hello-rpc-service' on port .
localhost:
start hello endpoint

启动RPC 服务使用者

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
// :: INFO SparkContext: Running Spark version 2.4.
// :: WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
// :: INFO SparkContext: Submitted application: test rpc
// :: INFO SecurityManager: Changing view acls to: boco
// :: INFO SecurityManager: Changing modify acls to: boco
// :: INFO SecurityManager: Changing view acls groups to:
// :: INFO SecurityManager: Changing modify acls groups to:
// :: INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(boco); groups with view permissions: Set(); users with modify permissions: Set(boco); groups with modify permissions: Set()
// :: INFO Utils: Successfully started service 'sparkDriver' on port .
// :: INFO SparkEnv: Registering MapOutputTracker
// :: INFO SparkEnv: Registering BlockManagerMaster
// :: INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
// :: INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
// :: INFO DiskBlockManager: Created local directory at C:\Users\boco\AppData\Local\Temp\blockmgr-6a0b8e7f-86d2-4bb8-b45c-7c04deabcb91
// :: INFO MemoryStore: MemoryStore started with capacity 901.8 MB
// :: INFO SparkEnv: Registering OutputCommitCoordinator
// :: WARN Utils: Service 'SparkUI' could not bind on port . Attempting port .
// :: INFO Utils: Successfully started service 'SparkUI' on port .
// :: INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://DESKTOP-JL4FSCV:4041
// :: INFO Executor: Starting executor ID driver on host localhost
// :: INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port .
// :: INFO NettyBlockTransferService: Server created on DESKTOP-JL4FSCV:
// :: INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
// :: INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: INFO BlockManagerMasterEndpoint: Registering block manager DESKTOP-JL4FSCV: with 901.8 MB RAM, BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, DESKTOP-JL4FSCV, , None)
// :: WARN Utils: Service 'hello-rpc-service' could not bind on port . Attempting port .
// :: INFO Utils: Successfully started service 'hello-rpc-service' on port .
// :: INFO TransportClientFactory: Successfully created connection to localhost/127.0.0.1: after ms ( ms spent in bootstraps)
bye, test askSync
Got the result = hi, neo
// :: INFO SparkUI: Stopped Spark web UI at http://DESKTOP-JL4FSCV:4041
// :: INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
// :: INFO MemoryStore: MemoryStore cleared
// :: INFO BlockManager: BlockManager stopped
// :: INFO BlockManagerMaster: BlockManagerMaster stopped
// :: INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
// :: INFO SparkContext: Successfully stopped SparkContext
// :: INFO ShutdownHookManager: Shutdown hook called
// :: INFO ShutdownHookManager: Deleting directory

此时 RPC 服务提供者打印信息如下:

receive test send
receive neo
receive test askSync
// :: WARN TransportChannelHandler: Exception in connection from /127.0.0.1:
java.io.IOException: 远程主机强迫关闭了一个现有的连接。
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:)
at sun.nio.ch.IOUtil.read(IOUtil.java:)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:)
at io.netty.util.concurrent.SingleThreadEventExecutor$.run(SingleThreadEventExecutor.java:)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:)
at java.lang.Thread.run(Thread.java:)

Spark(五十三):Spark RPC初尝试使用的更多相关文章

  1. Spark学习之路 (五)Spark伪分布式安装

    一.JDK的安装 JDK使用root用户安装 1.1 上传安装包并解压 [root@hadoop1 soft]# tar -zxvf jdk-8u73-linux-x64.tar.gz -C /usr ...

  2. Spark(五) -- Spark Streaming介绍与基本执行过程

    Spark Streaming作为Spark上的四大子框架之一,肩负着实时流计算的重大责任 而相对于另外一个当下十分流行的实时流计算处理框架Storm,Spark Streaming有何优点?又有何不 ...

  3. Spark2.2(三十三):Spark Streaming和Spark Structured Streaming更新broadcast总结(一)

    背景: 需要在spark2.2.0更新broadcast中的内容,网上也搜索了不少文章,都在讲解spark streaming中如何更新,但没有spark structured streaming更新 ...

  4. Spark入门(五)--Spark的reduce和reduceByKey

    reduce和reduceByKey的区别 reduce和reduceByKey是spark中使用地非常频繁的,在字数统计中,可以看到reduceByKey的经典使用.那么reduce和reduceB ...

  5. 【Spark 内核】 Spark 内核解析-上

    Spark内核泛指Spark的核心运行机制,包括Spark核心组件的运行机制.Spark任务调度机制.Spark内存管理机制.Spark核心功能的运行原理等,熟练掌握Spark内核原理,能够帮助我们更 ...

  6. 【Spark 内核】 Spark 内核解析-下

    Spark内核泛指Spark的核心运行机制,包括Spark核心组件的运行机制.Spark任务调度机制.Spark内存管理机制.Spark核心功能的运行原理等,熟练掌握Spark内核原理,能够帮助我们更 ...

  7. 初步了解Spark生态系统及Spark Streaming

    一.        场景 ◆ Spark[4]: Scope:  a MapReduce-like cluster computing framework designed for low-laten ...

  8. R语言爬虫初尝试-基于RVEST包学习

    注意:这文章是2月份写的,拉勾网早改版了,代码已经失效了,大家意思意思就好,主要看代码的使用方法吧.. 最近一直在用且有维护的另一个爬虫是KINDLE 特价书爬虫,blog地址见此: http://w ...

  9. 【译】Spark官方文档——Spark Configuration(Spark配置)

    注重版权,尊重他人劳动 转帖注明原文地址:http://www.cnblogs.com/vincent-hv/p/3316502.html   Spark主要提供三种位置配置系统: 环境变量:用来启动 ...

随机推荐

  1. 笔谈HTTP Multipart POST请求上传文件

    公司一做iOS开发的同事用HTTP Multipart POST请求上传语音数据,但是做了两天都没搞定,项目经理找到我去帮忙弄下.以前做项目只用过get.post,对于现在这个跟服务器交互的表单请求我 ...

  2. Audio Queue Services Programming Guide(音频队列服务编程指南)

    Audio Queue Services 的苹果官方文档: https://developer.apple.com/library/ios/documentation/MusicAudio/Conce ...

  3. ECharts大屏可视化【词云,堆积柱状图,折线图,南丁格尔玫瑰图】

    一.简介 参考ECharts快速入门:https://www.cnblogs.com/yszd/p/11166048.html 二.代码实现 <!DOCTYPE html> <htm ...

  4. 【RAC】rac环境下的数据库备份与还原

    [RAC]rac环境下的数据库备份与还原 一.1  BLOG文档结构图 一.2  前言部分 一.2.1  导读 各位技术爱好者,看完本文后,你可以掌握如下的技能,也可以学到一些其它你所不知道的知识,~ ...

  5. pycharm 专业注册

    pycharm的bin目录下pycharm.exe.vmoptions和pycharm64.exe.vmoptions两个配置文件添加 这个路径  -javaagent:E:\PyCharm 2017 ...

  6. Vue 路由守卫解决页面退出和弹窗的显示冲突

    在使用UI框架提供的弹出层Popup时,如Vant UI的popup,在弹出层显示时,点击物理按键或者小程序自带的返回时,会直接退出页面,这明显不符合页面逻辑. 解决思路: 在弹出层显示时,点击了返回 ...

  7. AD-logon workstation

    默认AD登录到限制为64个 原因 发生此问题的原因是User-Workstations属性的Range-Upper值为1,024个字符.使用Active Directory用户和计算机输入NetBIO ...

  8. 文件上传相关报错: The current request is not a multipart request或is a MultipartResolver configured?

    1:from中涉及到图片上传的就要用post提交方式.否则就会报这个错误. 2:第一中:在jsp页面的<head></head>标签里面加上<meta http-equi ...

  9. Linux——CentOS7没有ifconfig命令

    前言 今天新安装的centos7,使用ifconfig命令却提示没有,直接安装也没有~ 正文 直接安装直接告诉我这个包不是一个有效的 [root@kafka ~]# yum install -y if ...

  10. JavaScript——判断页面是否加载完成

    前言 接上文,既然你是做一个loading的效果,你总不能一直loading,当页面完成加载的时候你总要结束吧 步骤 先说下原生的方法,再讲jquery的方法,原理是一样的 JavaScript // ...