nameko中的http~nameko系列之三
使用flask建立对外的web访问,当然是一种非常容易的事情:在flask这个轻量级框架下,非常容易建立自己的web服务,在web服务的具体路由对应的方法中通过nameko.standalone.rpc包中的ClusterRpcProxy,即可实现调用其他微服务(参见系列三中的案例)
然后运行的时候,按照flask的运行方式,即可。
但是有时候,还是希望纯粹些,就使用nameko自己的管理方式,该怎么办。
nameko提供了http的插件,实例代码如下:
my_web_server.py
import json
from nameko.web.handlers import http
class HttpService:
name = "http_service"
@http('GET', '/get/<int:value>')
def get_method(self, request, value):
return json.dumps({'value': value})
@http('POST', '/post')
def do_post(self, request):
return u"received: {}".format(request.get_data(as_text=True))
@http('GET,PUT,POST,DELETE', '/multi')
def do_multi(self, request):
return request.method
说明:
1、 nameko.web.handlers中定义了http这个装饰器,使用类似@http('POST', '/post') 的写法,就可以让被装饰的方法,处理http的request。
2、整个定义服务的方式与rpc的相同,在服务类中,需要当以一个名称。
3、运行的时候,与rpc的微服务相同 nameko run my_web_server

基于整个思路,要开发一个api网关,只需要开发这一个http请求响应的微服务即可。具体的功能在微服务中实现。
4、缺省的运行端口是8000。这里有个问题,可以重复运行整个server,并不会报端口占用的错误
5、如果希望使用不同的端口运行,可以使用config
定义一个config.yaml文件,内容如下
WEB_SERVER_ADDRESS: 0.0.0.0:8001
运行的时候:nameko run my_web_server --config config.yaml
6、方法中调用微服务,使用nameko.standalone.rpc包中的ClusterRpcProxy
比如增加一个路由:
from nameko.standalone.rpc import ClusterRpcProxy
CONFIG = {'AMQP_URI': "amqp://guest:guest@localhost"}
@http('GET', '/hello')
def hello():
with ClusterRpcProxy(CONFIG) as rpc:
result = rpc.greeting_service.hello(name="jerry")
return result, 200
nameko文档中有如下一段话:
Nameko is not a web framework. It has built-in HTTP support but it’s limited to what is useful in the realm of microservices. If you want to build a webapp for consumption by humans you should use something like flask.
建议使用flask类似的web框架。