Junior
214
What is RPC?
Answer from AI
sobes.tech AI
RPC (Remote Procedure Call) is a protocol for communication between processes that allows a program to execute a function or procedure in another address space (usually on another computer in the network) as if it were executed locally.
Main components and principles:
- Client: Initiates the call to the remote procedure.
- Server: Provides the implementation of the remote procedure.
- Stub/Proxy (client side): Generated code that appears as a local function but actually packages call parameters into a message and sends it over the network.
- Skeleton/Stub (server side): Generated code that receives the message from the client, unpacks the parameters, calls the actual procedure on the server, and packages the result for sending back to the client.
- IDL (Interface Definition Language): Language used to describe the interface of remote procedures, which is used for generating stubs and skeletons.
Implementation types:
- Synchronous RPC: The client waits for a response from the server before continuing execution.
- Asynchronous RPC: The client is not blocked and can continue working while the server processes the request.
Examples of RPC frameworks in Python:
// Example of using gRPC (popular RPC framework)
// Service definition in a .proto file (IDL)
// syntax = "proto3";
// message Request { string name = 1; }
// message Reply { string message = 1; }
// service Greeter {
// rpc SayHello (Request) returns (Reply) {}
// }
// Client code (approximate logic)
// import grpc
// import greeter_pb2
// import greeter_pb2_grpc
//
// with grpc.insecure_channel('localhost:50051') as channel:
// stub = greeter_pb2_grpc.GreeterStub(channel)
// response = stub.SayHello(greeter_pb2.Request(name='World'))
// print("Greeter client received: " + response.message)
// Server code (approximate logic)
// import grpc
// import greeter_pb2
// import greeter_pb2_grpc
//
// class Greeter(greeter_pb2_grpc.GreeterServicer):
// def SayHello(self, request, context):
// return greeter_pb2.Reply(message='Hello, %s!' % request.name)
//
// # Starting the server
// # server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
// # greeter_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
// # server.add_insecure_port('[::]:50051')
// # server.start()
// # server.wait_for_termination()
Advantages:
- Ease of use (looks like a local call).
- Network interaction abstraction.
- Support for various languages.
Disadvantages:
- Implicit dependency on the network.
- Difficulties with network error handling.
- Debugging complexity.