Initial experience of Python microservice framework nameko

Python cat 2021-10-14 06:47:01
△ Click on the above “ Python cat ” Focus on  , reply “ 1 ” Get an e-book

Nameko Namely sliding aunt , A scientific name : Light hat scale umbrella

1. Preface

Hello everyone , I'm brother cat !

in consideration of Python Performance and efficiency ,Python Web The end has been tepid ,JAVA and Golang Our micro service ecosystem has been very prosperous , It is also widely used in enterprise application development

This article will introduce a Python Microservice framework :「 Nameko 」

2. Nameko Introduce

Nameko It's a small one 、 concise 、 Asynchronous communication micro service architecture

It uses RabbitMQ Message queuing as message middleware , Publisher based 、 Subscriber pattern

among , Consumers and producers are based on RPC To communicate

Project address :

3. Let's fight

Let's say Flask Let's talk about building Python The steps of microservices

3-1   install RabbitMQ And start up

It is recommended to use Docker install  RabbitMQ, With Centos For example

# 1、 Download a version of RabbitMQ Mirror image 
# MQ Version number :3.9.5
docker pull rabbitmq:3.9.5-management

# 2、 Look at the mirror image
docker images

# 3、 start-up MQ Containers
# p: Specify the application port and port Web Console port
# hostname: Host name
# e: environment variable
# RABBITMQ_DEFAULT_VHOST: Virtual machine name
# 3e83da0dc938:MQ Mirror image ID
docker run -d --name rabbitmq3.9.5 -p 5672:5672 -p 15672:15672 -v `pwd`/data:/var/lib/rabbitmq --hostname myRabbit -e RABBITMQ_DEFAULT_VHOST=my_vhost  -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin 3e83da0dc938

It should be noted that , start-up MQ When the container , utilize -p Two ports are specified

  • 5672

    Application access port

  • 15672

    Console Web Access port number

then , Open firewall 5672、15672 Port number

PS: If it's a cloud server , Additional security groups need to be configured

Last , In the browser, enter... Through the following connection MQ backstage Web Manage Pages

Address :http://ip Address :15672

3-2   Install dependency packages

Use pip Command to install in a virtual environment nameko、flask Dependency package

#  Install dependency packages 
# nameko
pip3 install nameko

# flask
pip3 install flask

3-3   Create a service producer Producer

Customize a class , Use name Property defines the name of the service as 「 generate_service 」

Then use the decorator 「 rpc 」 Specific methods in the registration service


from nameko.rpc import rpc

class GenerateService(object):
    #  Define the microservice name
    name = "generate_service"

    def hello_world(self, msg):
        print('hello,i am been called by customer( consumer ), Return message :{}'.format(msg))

        #  Return results
        return "Hello World!I Am a msg from producer!"

3-4   Release Registration service service

Use nameko The command registers the service in the target file to MQ in

#  Registration service 
# producer_service: Target file
# admin:admin:MQ User name and password
# ip Address :5672:MQ The server ip Address and application port number
# my_vhost: Virtual machine name
nameko run producer_service --broker amqp://admin:admin@ip Address :5672/my_vhost

among ,my_vhost Corresponding MQ The name of the virtual machine configured when the container starts

3-5  Flask Definition API And consumers call services

For demonstration purposes , Use here Flask Write a simple one API

First , Definition MQ Connection information

then , Write a  API Interface , The request method is GET

Last , Use  nameko Medium 「 ClusterRpcProxy 」 Get the consumer object to call the specific method in the service

from flask import Flask
from nameko.standalone.rpc import ClusterRpcProxy

app = Flask(__name__)

# MQ To configure
config_mq = {'AMQP_URI'"amqp://admin:admin@ip Address :5672/my_vhost"}

@app.route('/hello_world', methods=['GET'])
def call_service():
    with ClusterRpcProxy(config_mq) as rpc:
        #  Consumer invokes microservices ( producer ), Access to services ( producer ) The return value of
        result = rpc.generate_service.hello_world(msg="xag msg")

        #  Return results
        return result, 200

3-6   Test it

Use Postman Call the above API Interface , The consumer can call the method in the generator service , The complete process of getting the returned results

#  call API Interface

4. Last

On top of it Flask As an example, it explains the complete process of building micro Services

If it's something else Web frame (  such as  Django、FastAPI etc.  ) The integrated microservice process is similar , Just modify the build API  Part of the logic , For more advanced content, you can refer to the official documents

Official documents :

Python The cat technology exchange group is open ! In the group, there are in-service employees of the first and second tier large factories in China , There are also students at home and abroad , There are more than ten years old programming birds , There are also new people who have just entered primary and secondary schools , The learning atmosphere is good ! Students who want to join the group , Please reply in the public number 『 Communication group 』, Get brother cat's wechat ( No advertising party , If you are the one !)~

Not yet ? Try them

How to say Python Is the fastest language ?

To improve automation skills 10 piece Ansible article

Microsoft official launch Python course

Python craftsman : Techniques for getting functions to return results

Teach you how to use Python Realization HashMap data structure

Python Realization : Detailed explanation LRU Cache elimination algorithm

If you find this article helpful
welcome Forward share , Click to follow Python cat
Python cat
Python cat
Share Python Advanced 、Python philosophy 、 Article translation 、 Resources, tools, etc
143 Original content
official account
Please bring the original link to reprint ,thank
Similar articles