您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)如何進行實驗室站遷移Serverless,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
2 月份,TencentServerless 舉辦了系列在線課堂分享,講解了 Serverless 概念、架構(gòu)、最佳實踐以及如何開發(fā)一個 component 等技術(shù)知識。
因為對 Serverless 非常感興趣,每次都參加了直播學(xué)習(xí)并提交了課堂作業(yè),一路下來感覺還不錯,因此決定把自己的實驗室站遷移到 Serverless 試試看。
不得不感嘆互聯(lián)網(wǎng)時代科技的進步,之前我的實驗室站采用的是傳統(tǒng)方法發(fā)布網(wǎng)站的環(huán)境部署,雖然現(xiàn)在熟悉了操作并不覺得很麻煩,但是對于從來沒接觸過這塊的人來說就比較難懂了。
而現(xiàn)在有了 Serverless,就可以完全無視上面的操作步驟了,這里引用官網(wǎng)的兩段話:
Serverless Framework 可以幫您以更少的成本和開銷, 快速構(gòu)建 Serverless 應(yīng)用。它能夠完美支持無服務(wù)器應(yīng)用的開發(fā),部署,測試,監(jiān)控等環(huán)節(jié)。Serverless 是面向未來的運維方式。
Serverless 建立在下一代公共云服務(wù)之上,該服務(wù)僅在使用時自動擴容和收費。當規(guī)模,所用容量和成本管理實現(xiàn)自動化時,可節(jié)省 99% 的成本管理。
無服務(wù)器架構(gòu)是全新的,因此我們需要改變先前對老架構(gòu)和工作流的看法。Serverless Framework 的目標是以一種簡單,強大而優(yōu)雅的使用體驗為開發(fā)者、團隊提供開發(fā)和運行 serverless 應(yīng)用程序所需的所有工具。
這種方式非常方便,本人現(xiàn)在倒是覺得對于個人開發(fā)者來說,如果想構(gòu)建輕量應(yīng)用的話,用 Serverless 應(yīng)該會節(jié)省非常多的時間。當然 Serverless 對比傳統(tǒng)型應(yīng)用還是有區(qū)別的,目前它并不能完美支持,舉一個例子:Flask CLI 就不支持,不過相信隨著 Serverless 技術(shù)的發(fā)展,Serverless 的支持將更加全面。
對于企業(yè)開發(fā)者來說也是同理的,想快速上線一套網(wǎng)站的話,部署在一個服務(wù)器上倒是好說,可是當訪問量上升之后,需要擴容的時候就比較麻煩了,這時候你得在多個服務(wù)器上部署并且配置負載均衡等等。
對我個人來說,我覺得 Serverless 最大的優(yōu)點在于運維部署方面,通過 Serverless 部署,還是非常方便的。
Serverless Framework 是基于 Node.js 的開源 CLI,注:需 Node 8+ 全局安裝:
npm install serverless -g
這里沒有使用 cnpm 的原因是因為網(wǎng)絡(luò)還算 ok 沒有特別耗時,另外忘記了之前在哪里看到過 cnpm 不會更新 package-lock.json,因此也就沒有再去用第三方源。之后更新的話就
npm install serverless -g
官網(wǎng)的快速開始教程之后快速部署了個 demo,即:
serverless create -t tencent-nodejs
命令里的 tencent-nodejs 是眾多組件中的一個,組件列表:https://github.com/serverless/components
因為本人對 Flask 還算熟悉,所以干脆把部署這個 Component 當成 Hello World 好了。其中官網(wǎng)簡介里寫道:任何支持 WSGI(Web Server Gateway Interface)的 Python 服務(wù)端框架都可以通過該組件進行部署,例如 Falcon 框架等。
1) 創(chuàng)建新項目
通過 sls 直接根據(jù)模板創(chuàng)建服務(wù),Serverless github 上有很多模板 比如:https://github.com/serverless/components/tree/master/templates/tencent-flask
serverless create --template-url https://github.com/serverless/components/tree/master/templates/tencent-flask
源碼如下:
# -*- coding: utf8 -*- import json from flask import Flask, jsonify, request app = Flask(__name__) @app.route("/") def index(): return "Hello Flash" @app.route('/user', methods = ['POST']) def addUser(): # we must get request body from clound function event; event = request.environ['event'] user = json.loads(event['body']) return jsonify(data=user) @app.route("/user", methods = ['GET']) def listUser(): users = [{'name': 'test1'}, {'name': 'test2'}] return jsonify(data=users) @app.route("/user/<id>", methods = ['GET']) def getUser(id): return jsonify(data={'name': 'test1'})
不基于模板
在 Pycharm 創(chuàng)建一個新的 Flask 項目:LAB_Serverless 以區(qū)別之前的 LAB
源碼如下:
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
2) 配置Serverless
創(chuàng)建serverless.yml,這里更改了幾處配置
MyComponent: component: '@serverless/tencent-flask' inputs: region: ap-beijing functionName: LAB_Serverless code: ./ functionConf: timeout: 10 memorySize: 128 environment: variables: TEST: value Version: 2020-2-23_21:01:44 vpcConfig: subnetId: '' vpcId: '' apigatewayConf: protocol: https environment: test
創(chuàng)建.env,寫入密匙(因為懶得每次部署都得拿起手機掃一掃授權(quán)(^_?)☆
TENCENT_SECRET_ID=<rm> TENCENT_SECRET_KEY=<rm>
3) 部署
serverless 的縮寫是 sls,因此也可以用 sls 簡化命令。但是這里報錯了……報錯的原因是requirements文件夾不存在。
查看終端
Microsoft Windows [版本10.0.17763.1039] (c) 2018 Microsoft Corporation。保留所有權(quán)利。 D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless>sls --debug DEBUG─Resolving the template's static variables. DEBUG─Collecting components from the template. DEBUG─Downloading any NPM components found in the template. DEBUG─Analyzing the template's components dependencies. DEBUG─Creating the template's components graph. DEBUG─Syncing template state. DEBUG─Executing the template's components graph. DEBUG─Compressing function LAB_Serverless file to D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless\.serverless/LAB_Serverless.zip. (node:22500) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat 'D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless\. serverless\requirements'eploying at Object.statSync (fs.js:946:3) at Object.statSync (C:\Users\yuangezhizao\AppData\Roaming\npm\node_modules\serverless\node_modules\_graceful-fs@4.2.3@graceful-fs\polyfills.js:308:16 ) at WriteStream.<anonymous> (C:\Users\yuangezhizao\.serverless\components\registry\npm\@serverless\tencent-flask@0.2.0\node_modules\@serverless\tencen t-flask\node_modules\@serverless\tencent-scf\library\utils.js:124:20) at WriteStream.emit (events.js:304:20) at C:\Users\yuangezhizao\.serverless\components\registry\npm\@serverless\tencent-flask@0.2.0\node_modules\@serverless\tencent-flask\node_modules\grac eful-fs\graceful-fs.js:298:14 at C:\Users\yuangezhizao\.serverless\components\registry\npm\@serverless\tencent-flask@0.2.0\node_modules\@serverless\tencent-flask\node_modules\grac eful-fs\graceful-fs.js:325:16 at C:\Users\yuangezhizao\AppData\Roaming\npm\node_modules\serverless\node_modules\_graceful-fs@4.2.3@graceful-fs\graceful-fs.js:325:16 at FSReqCallback.oncomplete (fs.js:152:23) (node:22500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:22500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will termi nate the Node.js process with a non-zero exit code. 194s?MyComponent?canceled 終止批處理操作嗎(Y/N)? Y D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless>
然后去 .serverless 文件下的 Template.MyComponent.pyRequirements.json 文件中看到了requirements.txt。這里其實是故意操作的(特意沒添加requirements.txt),說明 requirements.txt 必須存在!
因此,去創(chuàng)建文件內(nèi)容為 Flask 的 requirements.txt
D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless>sls --debug DEBUG─Resolving the template's static variables. DEBUG─Collecting components from the template. DEBUG─Downloading any NPM components found in the template. DEBUG─Analyzing the template's components dependencies. DEBUG─Creating the template's components graph. DEBUG─Syncing template state. DEBUG─Executing the template's components graph. DEBUG─Generated requirements from D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless\requirements.txt in D:\yuangezhizao\Documents\PycharmProje cts\LAB_Serverless\.serverless\requirements.txt... DEBUG─Installing requirements from C:\Users\yuangezhizao\AppData\Local\Yugasun\serverless-python-requirements\Cache\2a1a661c4e3e6faadab5d001bc10cc3ac ccf648921aad7c279d94f138eaaf833_slspyc\requirements.txt ... DEBUG─Using download cache directory C:\Users\yuangezhizao\AppData\Local\Yugasun\serverless-python-requirements\Cache\downloadCacheslspyc DEBUG─Running ... DEBUG─Compressing function LAB_Serverless file to D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless\.serverless/LAB_Serverless.zip. DEBUG─Compressed function LAB_Serverless file successful DEBUG─Uploading service package to cos[sls-cloudfunction-ap-beijing-code]. sls-cloudfunction-default-LAB_Serverless-1582464464.zip DEBUG─Uploaded package successful D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless\.serverless/LAB_Serverless.zip DEBUG─Creating function LAB_Serverless DEBUG─Created function LAB_Serverless successful DEBUG─Setting tags for function LAB_Serverless DEBUG─Creating trigger for function LAB_Serverless DEBUG─Deployed function LAB_Serverless successful DEBUG─Starting API-Gateway deployment with name MyComponent.TencentApiGateway in the ap-beijing region DEBUG─Service with ID service-0ok85tqh created. DEBUG─API with id api-ivk6tk0y created. DEBUG─Deploying service with id service-0ok85tqh. DEBUG─Deployment successful for the api named MyComponent.TencentApiGateway in the ap-beijing region. MyComponent: region: ap-beijing functionName: LAB_Serverless apiGatewayServiceId: service-0ok85tqh url: http://service-0ok85tqh-1251901037.bj.apigw.tencentcs.com/test/ 44s?MyComponent?done D:\yuangezhizao\Documents\PycharmProjects\LAB_Serverless>
趁機看下部署成功之后的 .serverless 文件夾:
這里 Template.MyComponent.TencentCloudFunction.json 即云函數(shù)
{ "deployed": { "Name": "LAB_Serverless", "Runtime": "Python3.6", "Handler": "api_service.handler", "MemorySize": 128, "Timeout": 10, "Region": "ap-beijing", "Description": "This is a template function" } }
第三方包全在這里:
Template.MyComponent.TencentApiGateway.json 即 API 網(wǎng)關(guān)
{ "protocols": [ "http" ], "subDomain": "service-0ok85tqh-1251901037.bj.apigw.tencentcs.com", "environment": "test", "region": "ap-beijing", "service": { "value": "service-0ok85tqh", "created": true }, "apis": [ { "path": "/", "method": "ANY", "apiId": { "value": "api-ivk6tk0y", "created": true } } ] }
也就是說CLI自動幫我們創(chuàng)建SCF并將運行環(huán)境一并上傳,再創(chuàng)建API 網(wǎng)關(guān)配置到SCF的觸發(fā)器上。
apigatewayConf: protocol: https environment: test
到這里demo就搞定了,已經(jīng)可以正常訪問了 。
去云函數(shù)看實際運行環(huán)境,發(fā)現(xiàn)把.idea文件夾也給上傳了 另外,多了如下倆本地沒有的文件:
其實這就是Serverless的核心了,Serverless配置靜態(tài)頁面的原理自己是清楚的。比如Hexo就是生成頁面之后上傳到COS上就能訪問了。
但是,對于動態(tài)頁面就比較好奇了,這是怎么實現(xiàn)的呢?其實就是靠著serverless.wsgi 這個文件等等。能看到這個模塊描述:此模塊將 AWS APIGateway 代理請求轉(zhuǎn)換為 WSGI 請求。
""" This module converts an AWS API Gateway proxied request to a WSGI request. Inspired by: https://github.com/miserlou/zappa Author: Logan Raarup <logan@logan.dk> """
還是相當有意思的。
接下來就得一點兒一點兒進行遷移了,不難想到應(yīng)該有非常多的坑的,比如如何訪問自己的 MySQL、Redis、 MongoDB,再比如Celery計劃任務(wù),自己是用RabbitMQ 的消息隊列,這東西要怎么上云?
關(guān)于如何進行實驗室站遷移Serverless就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。