Nameko是Python下的一个微服务框架,小巧简洁,通过RabbitMq消息组件来实现RPC服务
Github:NameKo
一、准备工作
1.RabbitMq 使用docker安装
docker pull rabbitmq:3.7-management
docker run --hostname my-rabbit --name rabbitmq-borg -p 15672:15672 -p 25672:25672 -p 5672:5672 -d rabbitmq:3.7-management
docker 管理页面为 localhost:15672,默认用户名密码 guest、 guest。
2.Nameko安装,直接使用pip3 install nameko安装即可
二、测试代码
1、服务端 service
from nameko.rpc import rpc
class GreetingService:
name="greeting_service"
@rpc
def hello(self,name):
return name
使用@rpc 装饰器定义RPC服务
2、配置文件 config.yml
AMQP_URI: 'pyamqp://guest:guest@localhost'
WEB_SERVER_ADDRESS: '0.0.0.0:8000'
rpc_exchange: 'nameko-rpc'
max_workers: 10
parent_calls_tracked: 10
LOGGING:
version: 1
handlers:
console:
class: logging.StreamHandler
root:
level: DEBUG
handlers: [console]
运行服务 nameko run –config config.yml service1
3、客户端 使用
import cProfile
from nameko.standalone.rpc import ClusterRpcProxy
config = {
'AMQP_URI': "pyamqp://guest:guest@localhost"
}
def test():
with ClusterRpcProxy(config) as cluster_rpc:
rs=cluster_rpc.greeting_service.hello("hellø")
if __name__ == '__main__':
cProfile.run('test()')
4、上面使用cProfile测试性能
5914 function calls (5783 primitive calls) in 0.076 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
27/12 0.000 0.000 0.002 0.000 <frozen importlib._bootstrap>:1009(_handle_fromlist)
1次调用RPC开销在76毫秒
5、封装成http
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))
6、使用wrt测试,mac使用brew install wrt 安装即可
wrk -t1 -d20s -c100 http://127.0.0.1:8000/get/42
1个线程,持续20秒100个连接
Running 20s test @ http://127.0.0.1:8000/get/42
1 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 74.17ms 11.06ms 141.23ms 63.00%
Req/Sec 1.35k 204.27 1.72k 62.50%
26934 requests in 20.03s, 3.34MB read
Requests/sec: 1344.62
Transfer/sec: 170.70KB
响应时间和直接RPC请求差不多
QPS并发量1344/sec,只能说一般般吧