python 微服務方案


介紹

使用python做web開發面臨的一個最大的問題就是性能,在解決C10K問題上顯的有點吃力。有些異步框架Tornado、Twisted、Gevent 等就是為了解決性能問題。這些框架在性能上有些提升,但是也出現了各種古怪的問題難以解決。

在python3.6中,官方的異步協程庫asyncio正式成為標准。在保留便捷性的同時對性能有了很大的提升,已經出現許多的異步框架使用asyncio。

使用較早的異步框架是aiohttp,它提供了server端和client端,對asyncio做了很好的封裝。但是開發方式和最流行的微框架flask不同,flask開發簡單,輕量,高效。正是結合這些優點, 以Sanic為基礎,集成多個流行的庫來搭建微服務。 Sanic框架是和Flask相似的異步協程框架,簡單輕量,並且性能很高。本項目就是以Sanic為基礎搭建的python微服務框架。(思想適用於其他語言)

微服務設計原則個人總結:

X 軸 :指的是水平復制,很好理解,就是講單體系統多運行幾個實例,做個集群加負載均衡的模式。
Z 軸 :是基於類似的數據分區,比如一個互聯網打車應用突然或了,用戶量激增,集群模式撐不住了,那就按照用戶請求的地區進行數據分區,北京、上海、四川等多建幾個集群。簡單理解數據庫拆分,比如分庫分表
Y 軸 :就是我們所說的微服務的拆分模式,就是基於不同的業務拆分。

微服務總體架構:

    

 

特點

  • 使用sanic異步框架,簡單,輕量,高效。
  • 使用uvloop為核心引擎,使sanic在很多情況下單機並發甚至不亞於Golang。
  • 使用asyncpg為數據庫驅動,進行數據庫連接,執行sql語句執行。
  • 使用aiohttp為Client,對其他微服務進行訪問。
  • 使用peewee為ORM,但是只是用來做模型設計和migration。
  • 使用opentracing為分布式追蹤系統。
  • 使用unittest做單元測試,並且使用mock來避免訪問其他微服務。
  • 使用swagger做API標准,能自動生成API文檔。

服務端

使用sanic異步框架,有較高的性能,但是使用不當會造成blocking, 對於有IO請求的都要選用異步庫。添加庫要慎重。
sanic使用uvloop異步驅動,uvloop基於libuv使用Cython編寫,性能比nodejs還要高。

功能說明:

啟動前

  1.  
    @app.listener('before_server_start')
  2.  
    async def before_srver_start(app, loop):
  3.  
    queue = asyncio.Queue()
  4.  
    app. queue = queue
  5.  
    loop.create_task(consume(queue, app.config.ZIPKIN_SERVER))
  6.  
    reporter = AioReporter( queue=queue)
  7.  
    tracer = BasicTracer(recorder=reporter)
  8.  
    tracer.register_required_propagators()
  9.  
    opentracing.tracer = tracer
  10.  
    app.db = await ConnectionPool(loop=loop).init(DB_CONFIG)
  • 創建DB連接池
  • 創建Client連接
  • 創建queue, 消耗span,用於日志追蹤
  • 創建opentracing.tracer進行日志追蹤

中間件

  1.  
    @app.middleware('request')
  2.  
    async def cros(request):
  3.  
    if request.method == 'POST' or request.method == 'PUT':
  4.  
    request['data'] = request.json
  5.  
    span = before_request(request)
  6.  
    request['span'] = span
  7.  
     
  8.  
     
  9.  
    @app.middleware('response')
  10.  
    async def cors_res(request, response):
  11.  
    span = request['span'] if 'span' in request else None
  12.  
    if response is None:
  13.  
    return response
  14.  
    result = {'code': 0}
  15.  
    if not isinstance(response, HTTPResponse):
  16.  
    if isinstance(response, tuple) and len(response) == 2:
  17.  
    result.update({
  18.  
    'data': response[0],
  19.  
    'pagination': response[1]
  20.  
    })
  21.  
    else:
  22.  
    result.update({'data': response})
  23.  
    response = json(result)
  24.  
    if span:
  25.  
    span.set_tag('http.status_code', "200")
  26.  
    if span:
  27.  
    span.set_tag('component', request.app.name)
  28.  
    span.finish()
  29.  
    return response
  • 創建span, 用於日志追蹤
  • 對response進行封裝,統一格式

異常處理

對拋出的異常進行處理,返回統一格式

任務

創建task消費queue中對span,用於日志追蹤

異步處理

由於使用的是異步框架,可以將一些IO請求並行處理

Example:

  1.  
    async def async_request(datas):
  2.  
    # async handler request
  3.  
    results = await asyncio.gather(*[data[2] for data in datas])
  4.  
    for index, obj in enumerate(results):
  5.  
    data = datas[index]
  6.  
    data[0][data[1]] = results[index]
  7.  
     
  8.  
    @user_bp.get('/<id:int>')
  9.  
    @doc.summary("get user info")
  10.  
    @doc.description("get user info by id")
  11.  
    @doc.produces(Users)
  12.  
    async def get_users_list(request, id):
  13.  
    async with request.app.db.acquire(request) as cur:
  14.  
    record = await cur.fetch(
  15.  
    """ SELECT * FROM users WHERE id = $1 """, id)
  16.  
    datas = [
  17.  
    [record, 'city_id', get_city_by_id(request, record['city_id'])]
  18.  
    [record, 'role_id', get_role_by_id(request, record['role_id'])]
  19.  
    ]
  20.  
    await async_request(datas)
  21.  
    return record

get_city_by_id, get_role_by_id是並行處理。

相關連接

sanic

模型設計 & ORM

Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use。

ORM使用peewee, 只是用來做模型設計和migration, 數據庫操作使用asyncpg。

Example:

  1.  
    # models.py
  2.  
     
  3.  
    class Users(Model):
  4.  
    id = PrimaryKeyField()
  5.  
    create_time = DateTimeField(verbose_name='create time',
  6.  
    default=datetime.datetime.utcnow)
  7.  
    name = CharField(max_length=128, verbose_name="user's name")
  8.  
    age = IntegerField(null=False, verbose_name="user's age")
  9.  
    sex = CharField(max_length=32, verbose_name="user's sex")
  10.  
    city_id = IntegerField(verbose_name='city for user', help_text=CityApi)
  11.  
    role_id = IntegerField(verbose_name='role for user', help_text=RoleApi)
  12.  
     
  13.  
    class Meta:
  14.  
    db_table = 'users'
  15.  
     
  16.  
     
  17.  
    # migrations.py
  18.  
     
  19.  
    from sanic_ms.migrations import MigrationModel, info, db
  20.  
     
  21.  
    class UserMigration(MigrationModel):
  22.  
    _model = Users
  23.  
     
  24.  
    # @info(version="v1")
  25.  
    # def migrate_v1(self):
  26.  
    # migrate(self.add_column('sex'))
  27.  
     
  28.  
    def migrations():
  29.  
    try:
  30.  
    um = UserMigration()
  31.  
    with db.transaction():
  32.  
    um.auto_migrate()
  33.  
    print("Success Migration")
  34.  
    except Exception as e:
  35.  
    raise e
  36.  
     
  37.  
    if __name__ == '__main__':
  38.  
    migrations()
  • 運行命令 python migrations.py
  • migrate_v1函數添加字段sex, 在BaseModel中要先添加name字段
  • info裝飾器會創建表migrate_record來記錄migrate,version每個model中必須唯一,使用version來記錄是否執行過,還可以記錄author,datetime
  • migrate函數必須以migrate_開頭

相關連接

peewee

數據庫操作

asyncpg is the fastest driver among common Python, NodeJS and Go implementations

使用asyncpg為數據庫驅動, 對數據庫連接進行封裝, 執行數據庫操作。

不使用ORM做數據庫操作,一個原因是性能,ORM會有性能的損耗,並且無法使用asyncpg高性能庫。另一個是單個微服務是很簡單的,表結構不會很復雜,簡單的SQL語句就可以處理來,沒必要引入ORM。使用peewee只是做模型設計

Example:

  1.  
    sql = "SELECT * FROM users WHERE name=$1"
  2.  
    name = "test"
  3.  
    async with request.app.db.acquire(request) as cur:
  4.  
    data = await cur.fetchrow(sql, name)
  5.  
     
  6.  
    async with request.app.db.transaction(request) as cur:
  7.  
    data = await cur.fetchrow(sql, name)
  • acquire() 函數為非事務, 對於只涉及到查詢的使用非事務,可以提高查詢效率
  • tansaction() 函數為事務操作,對於增刪改必須使用事務操作
  • 傳入request參數是為了獲取到span,用於日志追蹤
  • TODO 數據庫讀寫分離

相關連接

asyncpg
benchmarks

客戶端

使用aiohttp中的client,對客戶端進行了簡單的封裝,用於微服務之間訪問。

Don’t create a session per request. Most likely you need a session per application which performs all requests altogether.
A session contains a connection pool inside, connection reusage and keep-alives (both are on by default) may speed up total performance.

Example:

  1.  
    @app.listener('before_server_start')
  2.  
    async def before_srver_start(app, loop):
  3.  
    app.client = Client(loop, url='http://host:port')
  4.  
     
  5.  
    async def get_role_by_id(request, id):
  6.  
    cli = request.app.client.cli(request)
  7.  
    async with cli.get('/cities/{}'.format(id)) as res:
  8.  
    return await res.json()
  9.  
     
  10.  
    @app.listener('before_server_stop')
  11.  
    async def before_server_stop(app, loop):
  12.  
    app.client.close()
  13.  
     

對於訪問不同的微服務可以創建多個不同的client,這樣每個client都會keep-alives

日志 & 分布式追蹤系統

裝飾器logger

  1.  
    @logger(type='method', category='test', detail='detail', description="des", tracing=True, level=logging.INFO)
  2.  
    async def get_city_by_id(request, id):
  3.  
    cli = request.app.client.cli(request)
  • type: 日志類型,如 method, route
  • category: 日志類別,默認為app的name
  • detail: 日志詳細信息
  • description: 日志描述,默認為函數的注釋
  • tracing: 日志追蹤,默認為True
  • level: 日志級別,默認為INFO

分布式追蹤系統

  • OpenTracing是以Dapper,Zipkin等分布式追蹤系統為依據, 建立了統一的標准。
  • Opentracing跟蹤每一個請求,記錄請求所經過的每一個微服務,以鏈條的方式串聯起來,對分析微服務的性能瓶頸至關重要。
  • 使用opentracing框架,但是在輸出時轉換成zipkin格式。 因為大多數分布式追蹤系統考慮到性能問題,都是使用的thrift進行通信的,本着簡單,Restful風格的精神,沒有使用RPC通信。以日志的方式輸出, 可以使用fluentd, logstash等日志收集再輸入到Zipkin。Zipkin是支持HTTP輸入的。
  • 生成的span先無阻塞的放入queue中,在task中消費隊列的span。后期可以添加上采樣頻率。
  • 對於DB,Client都加上了tracing

相關連接

opentracing
zipkin
jaeger

API接口

api文檔使用swagger標准。

Example:

  1.  
    from sanic_ms import doc
  2.  
     
  3.  
    @user_bp.post('/')
  4.  
    @doc.summary('create user')
  5.  
    @doc.description('create user info')
  6.  
    @doc.consumes(Users)
  7.  
    @doc.produces({'id': int})
  8.  
    async def create_user(request):
  9.  
    data = request['data']
  10.  
    async with request.app.db.transaction(request) as cur:
  11.  
    record = await cur.fetchrow(
  12.  
    """ INSERT INTO users(name, age, city_id, role_id)
  13.  
    VALUES($1, $2, $3, $4, $5)
  14.  
    RETURNING id
  15.  
    """, data['name'], data['age'], data['city_id'], data['role_id']
  16.  
    )
  17.  
    return {'id': record['id']}
  • summary: api概要
  • description: 詳細描述
  • consumes: request的body數據
  • produces: response的返回數據
  • tag: API標簽
  • 在consumes和produces中傳入的參數可以是peewee的model,會解析model生成API數據, 在field字段的help_text參數來表示引用對象
  • http://host:ip/openapi/spec.json 獲取生成的json數據

相關連接

swagger

Response 數據

在返回時,不要返回sanic的response,直接返回原始數據,會在Middleware中對返回的數據進行處理,返回統一的格式,具體的格式可以[查看]

單元測試

單元測試使用unittest。 mock是自己創建了MockClient,因為unittest還沒有asyncio的mock,並且sanic的測試接口也是發送request請求,所以比較麻煩. 后期可以使用pytest。

Example:

  1.  
    from sanic_ms.tests import APITestCase
  2.  
    from server import app
  3.  
     
  4.  
    class TestCase(APITestCase):
  5.  
    _app = app
  6.  
    _blueprint = 'visit'
  7.  
     
  8.  
    def setUp(self):
  9.  
    super(TestCase, self).setUp()
  10.  
    self._mock.get('/cities/1',
  11.  
    payload={'id': 1, 'name': 'shanghai'})
  12.  
    self._mock.get('/roles/1',
  13.  
    payload={'id': 1, 'name': 'shanghai'})
  14.  
     
  15.  
    def test_create_user(self):
  16.  
    data = {
  17.  
    'name': 'test',
  18.  
    'age': 2,
  19.  
    'city_id': 1,
  20.  
    'role_id': 1,
  21.  
    }
  22.  
    res = self.client.create_user(data=data)
  23.  
    body = ujson.loads(res.text)
  24.  
    self.assertEqual(res.status, 200)
  • 其中_blueprint為blueprint名稱
  • 在setUp函數中,使用_mock來注冊mock信息, 這樣就不會訪問真實的服務器, payload為返回的body信息
  • 使用client變量調用各個函數, data為body信息,params為路徑的參數信息,其他參數是route的參數

代碼覆蓋

  1.  
    coverage erase
  2.  
    coverage run --source . -m sanic_ms tests
  3.  
    coverage xml -o reports/coverage.xml
  4.  
    coverage2clover -i reports/coverage.xml -o reports/clover.xml
  5.  
    coverage html -d reports
  • coverage2colver 是將coverage.xml 轉換成 clover.xml,bamboo需要的格式是clover的。

相關連接

unittest
coverage

異常處理

使用 app.error_handler = CustomHander() 對拋出的異常進行處理

Example:

  1.  
    from sanic_ms.exception import ServerError
  2.  
     
  3.  
    @visit_bp.delete('/users/<id:int>')
  4.  
    async def del_user(request, id):
  5.  
    raise ServerError(error='內部錯誤',code=10500, message="msg")
    • code: 錯誤碼,無異常時為0,其余值都為異常
    • message: 狀態碼信息
    • error: 自定義錯誤信息
    • status_code: http狀態碼,使用標准的http狀態碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM