python实现RPC——xmlrpc库的简单使用

一、RPC介绍

RPC(Remote Procedure Call)远程过程调用,它是一种通过网络从远程计算机程序上请求服务。RPC 是一种设计,就是为了解决不同服务之间的调用问题,完整的 RPC 实现一般会包含有传输协议 和序列化协议这两个。

RPC采用客户端/服务器模式。请求程序就是一个客户端,而提供服务的程序就是一个服务器。首先,客户端调用进程发送一个请求信息到服务器端,然后等待应答信息。在服务器端,进程保持睡眠状态直到请求信息到达为止。当一个请求信息到达,服务器获得进程参数,然后执行对应的服务方法并返回结果给客户端,随后继续等待下一个请求信息,直到关闭服务器端进程为止。

Python3中,使用xmlrpc库实现RPC,分为xmlrpc.server和xmlrpc.client。

二、xmlrpc库使用例子

1.rpc服务器实现

rpc_server.py

from xmlrpc.server import SimpleXMLRPCServer


# 1.定义能被客户端调用的类
class MethodSet(object):
    @staticmethod
    def say_hello():
        print("MethodSet的方法正在被调用...")
        str1 = "hello rpc!"
        return str1


# 2.定义能被客户端调用的函数
def say_hi():
    print("say_hi 函数正在被调用...")
    str2 = "hi rpc~"
    return str2


# 3.注册一个函数或者类来响应XML-RPC请求,并启动XML-RPC服务器
def setup_socket_service(server_ip="localhost", server_port=6666):
    try:
        server = SimpleXMLRPCServer((server_ip, server_port))  # 初始化XML-RPC服务
        print('Server {} Listening on port {} ...'.format(server_ip, server_port))
        server.register_instance(MethodSet())  # 注册一个类
        server.register_function(say_hi)  # 注册一个函数
        server.serve_forever()  # 启动服务器并永久运行
    except Exception as ex:
        raise Exception('Setup socket server error:\n{}'.format(ex))


if __name__ == '__main__':
    setup_socket_service()

启动服务端(程序要一直运行,不要关闭):python rpc_server.py
启动后结果:

min@LAPTOP-E6G8RE06 MINGW64 /e/study/mat
$ python rpc_server.py
Server localhost Listening on port 6666 ...

2.客户端实现

rpc_client.py

from xmlrpc.client import ServerProxy


def setup_socket_client(ip_address, port=6666):
    proxy = ServerProxy('http://%s:%s/' % (ip_address, port), allow_none=True)
    print('Connect to {}:{} successful ...'.format(ip_address, port))

    ret1 = proxy.say_hello()   # 调用
    print('Received the ret1 is {}'.format(ret1))

    ret2 = proxy.say_hi()  # 调用
    print('Received the ret2 is {}'.format(ret2))


if __name__ == '__main__':
    setup_socket_client(ip_address='localhost')

启动客户端,发起请求。python rpc_client.py
调用结果(客户端):

min@LAPTOP-E6G8RE06 MINGW64 /e/study/mat
$ python rpc_client.py
Connect to localhost:6666 successful ...
Received the ret1 is hello rpc!
Received the ret2 is hi rpc~

调用结果(服务端):

min@LAPTOP-E6G8RE06 MINGW64 /e/study/mat
$ python rpc_server.py
Server localhost Listening on port 6666 ...
MethodSet的方法正在被调用...
127.0.0.1 - - [19/Jun/2021 19:58:11] "POST / HTTP/1.1" 200 -
say_hi 函数正在被调用...
127.0.0.1 - - [19/Jun/2021 19:58:13] "POST / HTTP/1.1" 200 -

猜你喜欢

转载自blog.csdn.net/weixin_45455015/article/details/118058401