RpcCallConText是为RpcEndpoint提供的一个回调,这个回调用来返回消息或者错误。 RpcCallContext是线程安全的,可以被任何线程调用。
reply: 向发送方回复一个消息。如果发送方是一个RpcEndpoint,那么它的receive方法会被调用。
sendFailure: 向发送方报告一个错误。
senderAddress: 得到发送方的地址。
/**
* A callback that [[RpcEndpoint]] can use it to send back a message or failure. It's thread-safe
* and can be called in any thread.
*/
private[spark] trait RpcCallContext {
/**
* Reply a message to the sender. If the sender is [[RpcEndpoint]], its [[RpcEndpoint.receive]]
* will be called.
*/
def reply(response: Any): Unit
/**
* Report a failure to the sender.
*/
def sendFailure(e: Throwable): Unit
/**
* The sender of this message.
*/
def senderAddress: RpcAddress
}
NettyRpcCallContext是RpcCallContext的抽象子类,把错误用RpcFailure包装起来。
LocalNettyRpcCallContext继承自NettyRpcCallContext,send的消息交给Promise.success方法。
RemoteNettyRpcCallContextr send方法,先把消息序列化。
private[netty] abstract class NettyRpcCallContext(override val senderAddress: RpcAddress)
extends RpcCallContext with Logging {
protected def send(message: Any): Unit
override def reply(response: Any): Unit = {
send(response)
}
override def sendFailure(e: Throwable): Unit = {
send(RpcFailure(e))
}
}
/**
* If the sender and the receiver are in the same process, the reply can be sent back via `Promise`.
*/
private[netty] class LocalNettyRpcCallContext(
senderAddress: RpcAddress,
p: Promise[Any])
extends NettyRpcCallContext(senderAddress) {
override protected def send(message: Any): Unit = {
p.success(message)
}
}
/**
* A [[RpcCallContext]] that will call [[RpcResponseCallback]] to send the reply back.
*/
private[netty] class RemoteNettyRpcCallContext(
nettyEnv: NettyRpcEnv,
callback: RpcResponseCallback,
senderAddress: RpcAddress)
extends NettyRpcCallContext(senderAddress) {
override protected def send(message: Any): Unit = {
val reply = nettyEnv.serialize(message)
callback.onSuccess(reply)
}
}