如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

這篇文章將為大家詳細(xì)講解有關(guān)如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

創(chuàng)新互聯(lián)是一家專注于網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)與策劃設(shè)計(jì),濱海新區(qū)網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:濱海新區(qū)等地區(qū)。濱海新區(qū)做網(wǎng)站價(jià)格咨詢:13518219792

前言

2 月份,TencentServerless 舉辦了系列在線課堂分享,講解了 Serverless 概念、架構(gòu)、最佳實(shí)踐以及如何開(kāi)發(fā)一個(gè) component 等技術(shù)知識(shí)。

因?yàn)閷?duì) Serverless 非常感興趣,每次都參加了直播學(xué)習(xí)并提交了課堂作業(yè),一路下來(lái)感覺(jué)還不錯(cuò),因此決定把自己的實(shí)驗(yàn)室站遷移到 Serverless 試試看。

1. TencentServerless 介紹

不得不感嘆互聯(lián)網(wǎng)時(shí)代科技的進(jìn)步,之前我的實(shí)驗(yàn)室站采用的是傳統(tǒng)方法發(fā)布網(wǎng)站的環(huán)境部署,雖然現(xiàn)在熟悉了操作并不覺(jué)得很麻煩,但是對(duì)于從來(lái)沒(méi)接觸過(guò)這塊的人來(lái)說(shuō)就比較難懂了。

而現(xiàn)在有了 Serverless,就可以完全無(wú)視上面的操作步驟了,這里引用官網(wǎng)的兩段話:

Serverless Framework 可以幫您以更少的成本和開(kāi)銷, 快速構(gòu)建 Serverless 應(yīng)用。它能夠完美支持無(wú)服務(wù)器應(yīng)用的開(kāi)發(fā),部署,測(cè)試,監(jiān)控等環(huán)節(jié)。Serverless 是面向未來(lái)的運(yùn)維方式。

Serverless 建立在下一代公共云服務(wù)之上,該服務(wù)僅在使用時(shí)自動(dòng)擴(kuò)容和收費(fèi)。當(dāng)規(guī)模,所用容量和成本管理實(shí)現(xiàn)自動(dòng)化時(shí),可節(jié)省 99% 的成本管理。

無(wú)服務(wù)器架構(gòu)是全新的,因此我們需要改變先前對(duì)老架構(gòu)和工作流的看法。Serverless Framework 的目標(biāo)是以一種簡(jiǎn)單,強(qiáng)大而優(yōu)雅的使用體驗(yàn)為開(kāi)發(fā)者、團(tuán)隊(duì)提供開(kāi)發(fā)和運(yùn)行 serverless 應(yīng)用程序所需的所有工具。

這種方式非常方便,本人現(xiàn)在倒是覺(jué)得對(duì)于個(gè)人開(kāi)發(fā)者來(lái)說(shuō),如果想構(gòu)建輕量應(yīng)用的話,用 Serverless 應(yīng)該會(huì)節(jié)省非常多的時(shí)間。當(dāng)然 Serverless 對(duì)比傳統(tǒng)型應(yīng)用還是有區(qū)別的,目前它并不能完美支持,舉一個(gè)例子:Flask CLI 就不支持,不過(guò)相信隨著 Serverless 技術(shù)的發(fā)展,Serverless 的支持將更加全面。

對(duì)于企業(yè)開(kāi)發(fā)者來(lái)說(shuō)也是同理的,想快速上線一套網(wǎng)站的話,部署在一個(gè)服務(wù)器上倒是好說(shuō),可是當(dāng)訪問(wèn)量上升之后,需要擴(kuò)容的時(shí)候就比較麻煩了,這時(shí)候你得在多個(gè)服務(wù)器上部署并且配置負(fù)載均衡等等。

對(duì)我個(gè)人來(lái)說(shuō),我覺(jué)得 Serverless 最大的優(yōu)點(diǎn)在于運(yùn)維部署方面,通過(guò) Serverless 部署,還是非常方便的。

2. 安裝 Serverless Framework

Serverless Framework 是基于 Node.js 的開(kāi)源 CLI,注:需 Node 8+ 全局安裝:

npm install serverless -g

這里沒(méi)有使用 cnpm 的原因是因?yàn)榫W(wǎng)絡(luò)還算 ok 沒(méi)有特別耗時(shí),另外忘記了之前在哪里看到過(guò) cnpm 不會(huì)更新 package-lock.json,因此也就沒(méi)有再去用第三方源。之后更新的話就

npm install serverless -g

官網(wǎng)的快速開(kāi)始教程之后快速部署了個(gè) demo,即:

serverless create -t tencent-nodejs

命令里的 tencent-nodejs 是眾多組件中的一個(gè),組件列表:https://github.com/serverless/components

3. 部署 Python Flask 框架

因?yàn)楸救藢?duì) Flask 還算熟悉,所以干脆把部署這個(gè) Component 當(dāng)成 Hello World 好了。其中官網(wǎng)簡(jiǎn)介里寫(xiě)道:任何支持 WSGI(Web Server Gateway Interface)的 Python 服務(wù)端框架都可以通過(guò)該組件進(jìn)行部署,例如 Falcon 框架等。

1) 創(chuàng)建新項(xiàng)目

  • 基于模板

通過(guò) 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)建一個(gè)新的 Flask 項(xiàng)目:LAB_Serverless 以區(qū)別之前的 LAB

如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

源碼如下:

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,寫(xiě)入密匙(因?yàn)閼械妹看尾渴鸲嫉媚闷鹗謾C(jī)掃一掃授權(quán)(^_?)☆

TENCENT_SECRET_ID=<rm>
TENCENT_SECRET_KEY=<rm>

3) 部署

serverless 的縮寫(xiě)是 sls,因此也可以用 sls 簡(jiǎn)化命令。但是這里報(bào)錯(cuò)了……報(bào)錯(cuò)的原因是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。這里其實(shí)是故意操作的(特意沒(méi)添加requirements.txt),說(shuō)明 requirements.txt 必須存在!

如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

因此,去創(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>

趁機(jī)看下部署成功之后的 .serverless 文件夾:

如何進(jìn)行實(shí)驗(yàn)室站遷移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"
  }
}

第三方包全在這里:

如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

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
      }
    }
  ]
}

也就是說(shuō)CLI自動(dòng)幫我們創(chuàng)建SCF并將運(yùn)行環(huán)境一并上傳,再創(chuàng)建API 網(wǎng)關(guān)配置到SCF的觸發(fā)器上。

apigatewayConf:
    protocol: https
    environment: test

到這里demo就搞定了,已經(jīng)可以正常訪問(wèn)了 。

如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

4. 原理深入

去云函數(shù)看實(shí)際運(yùn)行環(huán)境,發(fā)現(xiàn)把.idea文件夾也給上傳了 另外,多了如下倆本地沒(méi)有的文件:

如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless

其實(shí)這就是Serverless的核心了,Serverless配置靜態(tài)頁(yè)面的原理自己是清楚的。比如Hexo就是生成頁(yè)面之后上傳到COS上就能訪問(wèn)了。

但是,對(duì)于動(dòng)態(tài)頁(yè)面就比較好奇了,這是怎么實(shí)現(xiàn)的呢?其實(shí)就是靠著serverless.wsgi 這個(gè)文件等等。能看到這個(gè)模塊描述:此模塊將 AWS APIGateway 代理請(qǐng)求轉(zhuǎn)換為 WSGI 請(qǐng)求。

"""
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>
"""

還是相當(dāng)有意思的。

5. 遷移 LAB

接下來(lái)就得一點(diǎn)兒一點(diǎn)兒進(jìn)行遷移了,不難想到應(yīng)該有非常多的坑的,比如如何訪問(wèn)自己的 MySQL、redis、 MongoDB,再比如Celery計(jì)劃任務(wù),自己是用RabbitMQ 的消息隊(duì)列,這東西要怎么上云?

關(guān)于如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

分享題目:如何進(jìn)行實(shí)驗(yàn)室站遷移Serverless
URL鏈接:http://muchs.cn/article28/ishscp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、全網(wǎng)營(yíng)銷推廣、網(wǎng)站設(shè)計(jì)公司網(wǎng)站內(nèi)鏈、服務(wù)器托管、移動(dòng)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)