使用AWS SAM CLI Layer以加速构建
请问您有什么疑问吗?
- ビルドする時のnpm installが重い。
解决问题
-
- 依存モジュールはLayerとして切り出し。
-
- Lambda関数側は依存モジュールをdevDependenciesに入れてエディタ上はパスを通す
-
- (ビルドするとdevDependenciesはnode_modulesに入らないから、デプロイするLambda関数が肥大化する心配はない)。
-
- 開発中はキャッシュオプションをつけてLayerのビルドは短縮。
- sam build HelloWorldFunction -c
关于Layer
Layer被放置在/opt目录下的映像中。
所以只需将库放置在已设置路径的地方即可。
如果运行时是Node.js,那么默认情况下NODE_PATH被设置为/opt/nodejs/node_modules等路径。
所以,只需将库下载到nodejs/node_modules目录中,然后将其作为Layer部署即可。
nodejs是目录名的关键点。
请参考链接:https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
如果是SAM的情况,只要将本地目录指定为Layer,它会自动构建并部署。
使用者
正常导入
const { format } = require("date-fns");
exports.lambdaHandler = async (event, context) => {
try {
const d = format(new Date(2014, 1, 11), "yyyy-MM-dd");
console.log("d=" + d);
为了在编辑器上能够引用,请将其添加到devDependencies中。
使用npm安装date-fns lodash,保存至开发环境 (–save-dev)。
分层侧面
目录名称默认情况下必须是nodejs。
(也许可以自己设置NODE_PATH来更改)
下载库。
$ mkdir nodejs
$ cd nodejs
$ npm init
$ npm install date-fns lodash
模板
定义 Layer 并从 Function 中引用。
在 ContentUri 中写入本地目录的路径。
如果没有 Metadata,则无法构建 Layer。
遇到了 Import Error 的问题。
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-layerversion.html
也许有某种原因不能使用默认设置。
看起来可以进行各种定制。
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/building-layers.html
MyLayer:
Type: AWS::Serverless::LayerVersion
Properties:
Description: Layer description
ContentUri: "nodejs/"
CompatibleRuntimes:
- nodejs12.x
Metadata:
BuildMethod: nodejs12.x
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs12.x
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
Layers:
- !Ref MyLayer
搭建
显示已构建 Layer 和 Build。
$ sam build – 简化版
$ sam 构建
本地执行
我创建了一个本地层的形象。
$ sam local invoke HelloWorldFunction
Invoking app.lambdaHandler (nodejs12.x)
MyLayer is a local Layer in the template
Building image..
我成功地使用了Layer中的库。
INFO d=2014-02-11
使用现金选项进行建筑
当缓存命中时会发生这种情况。
$ sam build -c
Starting Build use cache
Valid cache found, ...
因为Layer不会进行修改,所以缓存会命中,无需卸载库,速度也会更快。
只有被修复的函数才会导致Cache无效。
sam build HelloWorldFunction -c
Cache is invalid, running build
...
Valid cache found, copying previously built resources from layer build
如果缓存未命中
如果比较node_modules,如果缓存没有命中,
就清理掉node_modules。
执行以下命令进行中文本地化的释义,只需一种选择:
$ npm prune
运行 npm prune 命令