Nameko is a framework for building microservices in Python.
The example requires RabbitMQ, because it’s using the Nameko built-in AMQP RPC features.
Nameko微服务框架基于RabbitMQ的RPC远程调用协议。
Django REST framework is a powerful and flexible toolkit for building Web APIs.

一、前提

安装并运行RabbitMQ
在开发环境中使用 RabbitMQ 最简单的方式就是运行其官方的 docker 容器。(安装过程略)

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

如果运行docker时没有指定用户名和密码,则使用默认值【guest】

docker run -d --hostname my-rabbit --name rabbit -e RABBITMQ_DEFAULT_USER=user -e RABBITMQ_DEFAULT_PASS=password -p 15672:15672 -p 5672:5672 rabbitmq:management

网址:http://localhost:15672/
rabbitMQ

二、发布Nameko微服务

2.1、Install with Pip

pip install nameko

2.2、Service code

from nameko.rpc import rpc


# A Nameko service is just a Python class
class ServiceRpc:
    # 微服务名称
    name = "service_rpc_hello"

    @rpc
    def hello(self, name):
        return {"result": "Hello, {}!".format(name)}

2.3、Running a Service

2.3.1、使用命令参数指定RabbitMQ服务

nameko run --broker amqp://guest:guest@192.168.0.46 service_rpc

2.3.2、使用yaml配置文件指定RabbitMQ服务

nameko run --config rabbitmq.yaml service_rpc

rabbitmq.yaml 文件内容,如下:

AMQP_URI: 'pyamqp://guest:guest@192.168.0.46'

console

浏览器效果查看,如下:
services

2.4、调用服务演示

from nameko.standalone.rpc import ClusterRpcProxy

config = {
    'AMQP_URI': 'pyamqp://guest:guest@192.168.0.46'
}


if __name__ == '__main__':
    with ClusterRpcProxy(config) as cluster_rpc:
    	# 同步调用
        res = cluster_rpc.service_rpc_hello.hello("firstname")
        print(res)
        # 异步调用
        res = cluster_rpc.service_rpc_hello.hello.call_async("asyname")
        print(res.result())

hello-cluster

三、Django调用Nameko微服务

创建Django官网示例mysite项目(略,参见:https://docs.djangoproject.com/zh-hans/2.0/intro/tutorial01/),示例代码使用DRF框架编写API接口。

3.1、pip install django_nameko

3.2、settings.py 增加nameko配置

# amqp地址
NAMEKO_CONFIG = {
    'AMQP_URI': 'amqp://guest:guest@192.168.101.46'
}
# 设置连接超时
NAMEKO_TIMEOUT = 10

3.3、api.py 后台接口

在polls文件夹中,新建api.py

from django_nameko import get_pool
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet


class NamekoViewSet(ModelViewSet):

    @action(detail=False, url_path='hello', methods=['GET'])
    def hello_msg(self, request, *args, **kwargs):
        name = self.request.query_params.get('name', 'world')
        try:
            with get_pool().next() as rpc:
                res = rpc.service_rpc_hello.hello(name)
                return Response({'result': 'hello {}!'.format(res)}, status=200)
        except Exception as e:
            print(e)
        return Response({'result': 'hello world!'}, status=200)

    @action(detail=False, url_path='hello_async', methods=['GET'])
    def hello_async(self, request, *args, **kwargs):
        name = self.request.query_params.get('name', 'world')
        try:
            with get_pool().next() as rpc:
                res = rpc.service_rpc_hello.hello.call_async(name)
                return Response(res.result(), status=200)
        except Exception as e:
            print(e)
        return Response({'result': 'hello world!'}, status=200)

3.4、urls.py

在polls的urls.py文件中,配置如下:

from .api import NamekoViewSet

router = routers.DefaultRouter()
router.register(r'', NamekoViewSet, basename='api')

3.5、浏览器查看效果

启动django项目

python manage.py runserver 0.0.0.0:8001

浏览器访问hello_async网址
hello-async

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐