Python远程过程调用RPC小例子

由于时效问题,该文某些代码、技术可能已经过期,请注意!!!本文最后更新于:1 年前

RPC demo

在B服务器上运行RPC服务

  • 服务端server.py代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # server.py
    import Pyro4

    @Pyro4.expose
    class MyServer:
    def do_something(self):
    return "hello from server"

    if __name__ == '__main__':
    daemon = Pyro4.Daemon(port=35721)
    uri = daemon.register(MyServer, objectId="helloworld")
    print("Ready. Object uri =", uri)
    daemon.requestLoop()
  • 执行程序
    1
    python server.py

在A服务器上运行RPC客户端

  • 客户端client.py代码
    1
    2
    3
    4
    5
    6
    7
    8
    # client.py
    import Pyro4

    # 输入server 端的uri
    server = Pyro4.Proxy("PYRO:helloworld@localhost:35721")

    result = server.do_something()
    print(result)
  • 执行程序
    1
    python client.py
    正常输出:hello from server

其他方法(由chatgpt生成)

  • 使用socket通信:可以在A服务器上编写一个Python程序,它将通过socket连接到B服务器,并发送需要执行的命令,B服务器将接收并执行该命令,并将结果返回给A服务器。

  • 使用远程过程调用(RPC):可以使用Python的RPC库,如Pyro或RPC4Django,以编写A服务器上的Python程序,它将调用B服务器上的Python程序。

  • 使用Web服务:可以在B服务器上编写一个Python Web服务,使用Flask、Django等Web框架,以接收来自A服务器的HTTP请求,并返回结果。在A服务器上,可以使用Python的requests库或类似的HTTP客户端库发送HTTP请求并获取结果。

  • 使用消息队列:可以使用消息队列,如RabbitMQ或Apache Kafka,以在A服务器和B服务器之间传递消息。在A服务器上,可以使用Python的pika或kafka-python库发送消息,而在B服务器上,可以使用相应的库来接收和处理消息。

使用socket通信
  • A服务器上的Python程序:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    import socket

    HOST = 'B服务器IP地址'
    PORT = B服务器监听的端口号

    # 建立socket连接
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))

    # 发送命令到B服务器
    cmd = 'python /path/to/python/program.py'
    s.sendall(cmd.encode())

    # 获取B服务器返回的结果
    data = s.recv(1024)
    print('Received:', data.decode())

    # 关闭连接
    s.close()

  • B服务器上的Python程序:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import subprocess

    while True:
    # 监听端口
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()

    # 接收来自A服务器的命令
    cmd = conn.recv(1024).decode()

    # 执行命令并返回结果
    result = subprocess.run(cmd, shell=True, capture_output=True)
    conn.sendall(result.stdout)

使用Web服务
  • 在B服务器上使用Flask框架创建Web服务:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # app.py
    from flask import Flask

    app = Flask(__name__)

    @app.route('/do_something')
    def do_something():
    return "hello from server"

    if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

  • 在A服务器上使用requests库发送HTTP请求:
    1
    2
    3
    4
    5
    6
    7
    import requests

    url = 'B服务器IP地址:5000/do_something'
    response = requests.get(url)

    print(response.text)

使用消息队列
  • 在A服务器上使用pika库发送消息到消息队列:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import pika

    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='task_queue', durable=True)

    message = 'python /path/to/python/program.py'
    channel.basic_publish(exchange='',
    routing_key='task_queue',
    body=message,
    properties=pika.BasicProperties(
    delivery_mode=2, # make message persistent
    ))

    print(" [x] Sent %r" % message)
    connection.close()

  • 在B服务器上使用pika库接收消息并处理:
    1
    2
    3
    4
    5
    6
    7
    8
    import pika
    import subprocess

    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='task_queue',


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!