python and RPC services

RPC

1. What is RPC

  • RPC is to solve the information exchange between the invention and existing services.

  • RPC (Remote Procedure Call) - remote procedure call, which is a service request from a remote computer through a network, without having to understand the underlying network protocol technology.

    RPC采用客户机/服务器模式。请求程序就是一个客户机,而服务提供程序就是一个服务器。
    
    首先,客户机调用进程发送一个有进程参数的调用信息到服务进程,然后等待应答信息。
    
    在服务器端,进程保持睡眠状态直到调用信息到达为止。
    
    当一个调用信息到达,服务器获得进程参数,计算结果,发送答复信息
    
    然后等待下一个调用信息,最后,客户端调用进程接收答复信息,获得进程结果,然后调用执行继续进行。

RPC就是一种远程调用函数接口的方式,说白了,就是一种远程调用函数接口的方式,客户端和服务端之间约定一种契约(函数接口),然后服务端一直等待客户端的调用。

有点像平常的WEB网络请求。

一种用途是在多台服务器之间互相进行调用。

另一个用途则在于,不同编程语言之间都支持这种方式,像Python更是内置对其的支持,不需要额外安装什么库,所以可以直接在多语言的服务器之间互相进行调用。

Socket编程就是RPC通信

2.xmlrp library

  • Simple server
  • Like web request, we need to identify for clients accessing the url and port number, as well as methods for the realization of client calls, we finally let the server has been in a state of waiting to be visited:
  • rpc_server.py
from xmlrpc.server import SimpleXMLRPCServer

# 调用函数
def respon_string(str):
    return "get string:%s"%str


if __name__ == '__main__':
    server = SimpleXMLRPCServer(('localhost', 8888)) # 初始化
    server.register_function(respon_string, "get_string") # 注册get_string函数
    print ("Listening for Client")
    server.serve_forever() # 保持等待调用状态
  • rpc_client.py
from xmlrpc.client import ServerProxy

if __name__ == '__main__':
    server = ServerProxy("http://localhost:8888") # 初始化服务器
    print (server.get_string("RPC RPC")) # 调用get_string函数并传参,调用get_string让服务端通过respon_string函数处理请求,并返回。
  • operating
#服务端启动:
[root@xujunk tmp]#python3 rpc_server.py
Listening for Client
#客户端启动:
[root@xujunk tmp]#python3 rpc_client.py 
get string:RPC RPC      #返回结果

#服务端接到请求:
127.0.0.1 - - [22/Sep/2019 00:12:03] "POST /RPC2 HTTP/1.1" 200 -

Guess you like

Origin www.cnblogs.com/xujunkai/p/11567005.html
RPC
RPC