想象一下,你有一个 REST API ,这个 API 有一个端点(LCTT 译注:REST 风格的 API 可以有多个端点用于处理对同一资源的不同类型的请求)用来接受数据,并且你需要将接收到的数据进行一些运算工作。那么相比阻塞接口调用者的请求来说,异步实现此接口是一个更好的选择。你可以先给用户返回一个 “OK - 你的请求稍后会处理” 的状态,然后在后台任务中完成运算。
(service_env)$ nameko run service --broker amqp://guest:guest@localhost starting services: mail, compute Connected to amqp://guest:**@127.0.0.1:5672// Connected to amqp://guest:**@127.0.0.1:5672//
@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: # asynchronously spawning and email notification rpc.mail.send.async(email, subject, msg) # asynchronously spawning the compute task result = rpc.compute.compute.async(operation, value, other, email) return msg, 200
app.run(debug=True)
在其他的 shell 或者服务器上运行此文件
1 2 3
(api_env) $ python api.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)