一:rabbitmq install
docker run -p 5672:5672 --hostname nameko-rabbitmq rabbitmq:3
rabbitmq相当于一个消息队列(也就是消息中间件),nameko run 运行的服务都会挂载到rabbitmq上,所以用nameko搭建微服务必须先安装rabbitmq。
二:微服务类
- 创建一个service1.py 写入以下内容。
from nameko.rpc import rpc
class GreetingService:
name = "greeting_service"
@rpc
def hello(self, name):
return "Hello, {}!".format(name)
- init.py 文件内容
from .service1.service1 import GreetingService
三:微服务启动方式一
nameko run 文件名 &
(暂时还没实践,)
四:微服务启动方式二
- 创建一个 config.yaml 文件
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]
&符是代表linux语言,表示这个命令在后台运行。
nameko run --config config.yaml services:GreetingService &
五:flask服务器调用微服务
from flask import Flask
from nameko.standalone.rpc import ClusterRpcProxy
CONFIG = {'AMQP_URI': "amqp://guest:guest@localhost"}
app = Flask(__name__)
@app.route('/')
def hello_world():
with ClusterRpcProxy(CONFIG) as rpc:
result = rpc.greeting_service.hello(name="jerry")
return result, 200
目录参考
参考的链接
https://zhuanlan.zhihu.com/p/82924225
https://blog.csdn.net/eagleuniversityeye/article/details/102722741
https://www.jianshu.com/p/9d8802c92ba6
https://www.jianshu.com/p/13bd0b564216
以下是第二次测试所用数据
前提安装好了rabbitmq
1: hello_service.py发布服务,服务名称为“hello_service”
from nameko.rpc import rpc
class hello_service:
name = "hello_service"
@rpc
def hello(self):
print("hello world")
启动微服务的命令和第一次有区别,直接用命令行启动的。
后面的ip是自己服务器ip
nameko run hello_service --broker amqp://guest:guest@39.102.59.187
flask里的代码
from flask import Flask
from nameko.standalone.rpc import ClusterRpcProxy
CONFIG = {'AMQP_URI': "amqp://guest:guest@39.102.59.187"}
app = Flask(__name__)
@app.route('/')
def hello_world():
with ClusterRpcProxy(CONFIG) as rpc:
result = rpc.hello_service.hello(name="jerry")
return result, 200
Nginx里的配置
server {
# 监听81端口
listen 8080;
listen [::]:8080;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# 请求转发到gunicorn服务器
proxy_pass http://127.0.0.1:5003;
# 请求转发到多个gunicorn服务器
# proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
# 设置请求头,传递原始请求ip给gunicorn服务器
proxy_set_header X-Real-IP $remote_addr;
}
}
最后用gunicorn启动flask项目,指定127.0.0.1:5003
通过39.102.59.187:8080访问
nameko run face_service --broker amqp://admin:admin@10.84.62.199/my_vhost