Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> 學習 Linux

用 Python、RabbitMQ 與 Nameko 動手做一套微服務

微服務為什麼值得做

把系統切成多個獨立部署、各自負責單一職責的小服務,已經成為讓程式碼持續演進的常見選擇。M. Fowler 對它的描述是:以服務套件形式組成的應用設計方式。這些服務彼此不感知對方內部實作,只透過事先定義好介面與通訊協定(通常是訊息佇列)交換訊息。

舉例來說,一個 REST 介面收到資料後需要做運算。與其讓呼叫端阻塞等待,不如先回覆「已收到,稍後處理」,把運算丟到背景任務;運算完成後要寄信通知,也可以交由另一個服務負責。Python 生態系中的 Nameko 就是把這件事變簡單的框架。

用 Python、RabbitMQ 與 Nameko 動手做一套微服務

環境準備

  • 可運作的 RabbitMQ(常見的訊息佇列實作)
  • 以 VirtualEnv 建立的 services 虛擬環境
  • 以 VirtualEnv 建立的 api 虛擬環境

啟動 RabbitMQ

開發階段最省事的方式是跑官方 Docker 映像:

docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management

瀏覽器開啟 https://localhost:15672 ,能用 guest:guest 登入管理介面即代表成功。

用 Python、RabbitMQ 與 Nameko 動手做一套微服務

建立服務環境

$ mkdir myproject
$ cd myproject
$ virtualenv service_env
$ source service_env/bin/activate
(service_env)$ pip install nameko
(service_env)$ pip install yagmail

撰寫服務程式

把兩個服務放在同一個模組裡最方便,當然也可以拆成不同模組各自啟動。建立 service.py:

import yagmail
from nameko.rpc import rpc, RpcProxy

class Mail(object):
    name = "mail"

    @rpc
    def send(self, to, subject, contents):
        yag = yagmail.SMTP('myname@gmail.com', 'mypassword')
        # 實際環境請從安全的設定來源讀取憑證,例如 Dynaconf
        yag.send(to=to.encode('utf-8'),
                 subject=subject.encode('utf-8'),
                 contents=[contents.encode('utf-8')])

class Compute(object):
    name = "compute"
    mail = RpcProxy('mail')

    @rpc
    def compute(self, operation, value, other, email):
        operations = {
            'sum': lambda x, y: int(x) + int(y),
            'mul': lambda x, y: int(x) * int(y),
            'div': lambda x, y: int(x) / int(y),
            'sub': lambda x, y: int(x) - int(y)
        }
        try:
            result = operations[operation](value, other)
        except Exception as e:
            self.mail.send.async(email, "An error occurred", str(e))
            raise
        else:
            self.mail.send.async(
                email,
                "Your operation is complete!",
                "The result is: %s" % result
            )
            return result

啟動服務(正式環境建議改用 supervisord 之類的行程管理器,而不是停在前景的終端機):

(service_env)$ nameko run service --broker amqp://guest:guest@localhost

測試服務

另開一個 shell,同樣在虛擬環境中進入互動介面:

(service_env)$ nameko shell --broker amqp://guest:guest@localhost

此時可透過 n.rpc 物件直接呼叫:

>>> n.rpc.mail.send("name@email.com", "testing", "Just testing")
>>> n.rpc.compute.compute('sum', 30, 10, "name@email.com")
40
>>> n.rpc.compute.compute('sub', 30, 10, "name@email.com")
20
>>> n.rpc.compute.compute('mul', 30, 10, "name@email.com")
300
>>> n.rpc.compute.compute('div', 30, 10, "name@email.com")
3

每次呼叫計算服務時,都會附帶觸發一次非同步的郵件通知。

在 API 端呼叫微服務

API 可以放在另一台機器上,環境如下:

$ virtualenv api_env
$ source api_env/bin/activate
(api_env)$ pip install nameko
(api_env)$ pip install flask
(api_env)$ pip install flasgger

API 端不需要 yagmail,寄信是服務的職責。建立 api.py:

from flask import Flask, request
from flasgger import Swagger
from nameko.standalone.rpc import ClusterRpcProxy

app = Flask(__name__)
Swagger(app)

CONFIG = {'AMQP_URI': "amqp://guest:guest@localhost"}

@app.route('/compute', methods=['POST'])
def compute():
    """ Micro Service Based Compute and Mail API
    This API is made with Flask, Flasgger and Nameko
    ---
    parameters:
      - name: body
        in: body
        required: true
        schema:
          id: data
          properties:
            operation:
              type: string
              enum: [sum, mul, sub, div]
            email:
              type: string
            value:
              type: integer
            other:
              type: integer
    responses:
      200:
        description: Please wait the calculation, you'll receive an email with results
    """
    operation = request.json.get('operation')
    value = request.json.get('value')
    other = request.json.get('other')
    email = request.json.get('email')

    msg = "Please wait the calculation, you'll receive an email with results"
    subject = "API Notification"

    with ClusterRpcProxy(CONFIG) as rpc:
        rpc.mail.send.async(email, subject, msg)
        result = rpc.compute.compute.async(operation, value, other, email)
    return msg, 200

app.run(debug=True)
(api_env)$ python api.py

接著拜訪 https://localhost:5000/apidocs/index.html ,Flasgger 產生的互動文件就能派送任務到佇列,由服務端消費。

用 Python、RabbitMQ 與 Nameko 動手做一套微服務

服務端的日誌會印在執行 nameko run 的終端機上,也可以到 RabbitMQ 管理介面觀察訊息在佇列中的流動。Nameko 還有更多進階特性,詳見 https://nameko.readthedocs.org/en/stable/ 。

Copyright © Linux教程網 All Rights Reserved