aws-lambda - RIP Tutorial · It is an unofficial and free aws-lambda ebook created for educational...
Transcript of aws-lambda - RIP Tutorial · It is an unofficial and free aws-lambda ebook created for educational...
aws-lambda
#aws-
lambda
1
1: aws-lambda 2
2
2
Lambda 2
Examples 2
2
Java AWS-Lambda S3 7
2: Alexa-KIT 9
Examples 9
Alexa 9
3: AWS LambdaPython 11
Examples 11
AWS Lambda 11
Hello World - Lambda 11
4: AWS LambdaS3 22
Examples 22
JavaEchoArgs 22
5: aws-lambdaC 23
23
23
23
Examples 23
1.Visual Studio 23
2. 25
3 - LambdaAWS 27
4.Visual StudioAWS Lambda 28
6: S3AWS Lambda 30
30
Examples 30
cheatsheet 30
javascriptAWS-SDK 30
30
S3 30
Elasticache Redis 30
7: 32
32
32
Examples 32
32
CRUD 32
8: S3aws-lambda 39
39
39
39
39
39
39
Examples 39
S3 PUT 39
41
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: aws-lambda
It is an unofficial and free aws-lambda ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official aws-lambda.
The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/zh-CN/home 1
1: aws-lambda
AWS Lambda。Amazon Web Services。Lambda。。
AWS LambdaNode.jsJavaScriptPythonJavaJava 8C.NET Core。。
HTTP
•AWSAmazon API GatewayREST•
Lambda○
○
○
○
•
••
Web•AWS•
Examples
AWS“ ”“ Lambda ”。1.
Lambda 。 2.
。LambdaLambda。 3.
https://riptutorial.com/zh-CN/home 2
https://riptutorial.com/zh-CN/home 5
Java AWS-Lambda S3
AWS-Lambda。/lambda。
Lambda
lambda。maven
<dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-core</artifactId> <version>1.1.0</version> <type>jar</type> </dependency> <dependency>
https://riptutorial.com/zh-CN/home 7
<groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-events</artifactId> <version>1.3.0</version> <type>jar</type> </dependency> </dependencies>
HelloWorld
package com; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.s3.event.S3EventNotification; public class HelloWorld implements RequestHandler< S3Event, String> { @Override public String handleRequest(S3Event event, Context ctx) { S3EventNotification.S3EventNotificationRecord record=event.getRecords().get(0); System.out.println("Bucket Name is "+record.getS3().getBucket().getName()); System.out.println("File Path is "+record.getS3().getObject().getKey()); return null; } }
mvn。
AWS-Lambda。Lambda“lambda”。Java。
“”。lambdaJava。
“”“.ZIP”.zip。
Handler。RequestHandler。lambdaLambda。“com.HelloWorld”
S3Lambda
S3
S3“”。•
“”“”。•
。“”Lambda。“ObjectCreatedAll”lambdabucket•
“Sends to”Lambdalambda。•
Lambda
lambda。lambda“CloudWatch”“Logs”Lambda。“Log Streams”。lambda。
aws-lambda https://riptutorial.com/zh-CN/aws-lambda/topic/2357/aws-lambda
https://riptutorial.com/zh-CN/home 8
2: Alexa-KIT
Examples
Alexa
AWSAWS Lambda。 。
node.jspython
alexa。。
。。
Configure functionlambda。
https://riptutorial.com/zh-CN/home 9
。
。
alexa。
。
Alexa-KIT https://riptutorial.com/zh-CN/aws-lambda/topic/7698/alexa-kit
https://riptutorial.com/zh-CN/home 10
3: AWS LambdaPython
Examples
AWS Lambda
AWS Lambda
••
AWS••
RESTful•AWS APIRESTful•
Hello World - Lambda
lambda。Hello World。 。
AWS1. Lambda2. “Lambda” 3.
4.
https://riptutorial.com/zh-CN/home 11
configure5.
https://riptutorial.com/zh-CN/home 12
https://riptutorial.com/zh-CN/home 13
API6. 。 7.
https://riptutorial.com/zh-CN/home 14
https://riptutorial.com/zh-CN/home 15
API NameAPI 。 LambdaURL。http。GET。AWSstagingproddev...proddev。Open。API NameAPI 。 LambdaURL。http。GET。AWSstagingproddev...proddev。Open。
8.
https://riptutorial.com/zh-CN/home 16
https://riptutorial.com/zh-CN/home 17
。python。。
cloudtrailaws lambda。。
9.
Lambda10.
https://riptutorial.com/zh-CN/home 18
https://riptutorial.com/zh-CN/home 19
lambda_function。lambda。。11.
。aws
12.
https://riptutorial.com/zh-CN/home 20
lambda。
AWS LambdaPython https://riptutorial.com/zh-CN/aws-lambda/topic/6698/aws-lambdapython
https://riptutorial.com/zh-CN/home 21
4: AWS LambdaS3
Examples
JavaEchoArgs
。Java
public String handleRequest(String input, Context context) { context.getLogger().log("Input: " + input); String output = "Input:" + System.getProperty("line.separator") + input; return output; }
AWS LambdaS3 https://riptutorial.com/zh-CN/aws-lambda/topic/6216/aws-lambdas3
https://riptutorial.com/zh-CN/home 22
5: aws-lambdaC
AWSAWS LambdaC。Visual Studio 2015CAWS Lambda。
“”。
20171。Windows 10 Home。
Visual Studio 201531. Visual Studio 2015AWS Toolkit - 1.11.2.02. Microsoft .NET2 - 14.1.21111.03.
。
。
WindowsWindows。
Examples
1.Visual Studio
Visual Studio - >1. AWS Lambda.NET Core 2.
https://riptutorial.com/zh-CN/home 23
“ ”。Empty FunctionFinish 3.
- > NuGet - >。4. Install-Package Amazon.Lambda.Core5. “”。。6.
https://riptutorial.com/zh-CN/home 24
2.
Function.cs
public class Function { /// <summary> /// A simple function that takes a birth date and returns Age in years /// </summary> /// <param name="input"></param> /// <returns>Age is years</returns> /// [LambdaSerializer(typeof(SimpleSerializer))] public string FunctionHandler(Dictionary<string, int> input) { var defaultMessage = "Age could not be determined."; var birthDate = new DateTime(input["year"], input["month"], input["day"]); var ageInYears = DateTime.Today.Year - birthDate.Year; if (birthDate.DayOfYear > DateTime.Today.DayOfYear) ageInYears--; defaultMessage = $"Age in years: {ageInYears}"; return defaultMessage; } }
1.
using System.Collections.Generic; using Amazon.Lambda.Core;
SimpleSerializer.cs2. 3.
using System;
https://riptutorial.com/zh-CN/home 25
using System.IO; using Amazon.Lambda.Core; using Newtonsoft.Json; namespace AWSLambdaFunctionAgeInYears { public class SimpleSerializer : ILambdaSerializer { public T Deserialize<T>(Stream requestStream) { string text; using (var reader = new StreamReader(requestStream)) text = reader.ReadToEnd(); try { return JsonConvert.DeserializeObject<T>(text); } catch (Exception ex) { if (typeof(T) == typeof(System.String)) return (T)Convert.ChangeType(text, typeof(T)); throw ex; } } public void Serialize<T>(T response, Stream responseStream) { StreamWriter streamWriter = new StreamWriter(responseStream); try { string text = JsonConvert.SerializeObject(response); streamWriter.Write(text); streamWriter.Flush(); } catch (Exception ex) { if (typeof(T) == typeof(System.String)) { streamWriter.Write(response); streamWriter.Flush(); return; } throw ex; } } } }
Test ProjectFunctionTest.cs23
var upperCase = function.FunctionHandler(null);
4.
- 。5.
https://riptutorial.com/zh-CN/home 26
3 - LambdaAWS
AWS Lambda ...1.
“AWS Lambda”。。。AWSLambdaFunctionAgeInYears“”。 2.
Role NameAWSLambdaRole。。 3.
https://riptutorial.com/zh-CN/home 27
4.Visual StudioAWS Lambda
3Visual StudioView Function。1. Sample Inputjson2.
{ "month": "10", "day": "28", "year": "1979" }
https://riptutorial.com/zh-CN/home 28
“ ”。AWS。3.
aws-lambdaC https://riptutorial.com/zh-CN/aws-lambda/topic/8937/aws-lambda-c--
https://riptutorial.com/zh-CN/home 29
6: S3AWS Lambda
LambdaAWS。S3。lambdaAWS-SDKLambdaS3S3Lambda
Examples
cheatsheet
javascriptAWS-SDK
Lambdaaws-sdk https://aws.amazon.com/sdk-for-node-js/ zip。
const AWS = require('aws-sdk');
module.exports.myFunction = (event, context, callback) => { const response = { statusCode: 200, body: 'Hello Lambda!', }; return callback(null, response); };
S3
const s3 = new AWS.S3;
Elasticache Redis
//make sure redis node-module is added in zip const redis = require('redis'); //the redis information should be stored in the environment, not hard coded const redis_options = { host: process.env.REDIS_HOST, port: process.env.REDIS_PORT }; module.exports.myFunction = (event, context, callback) => { try { let client = redis.createClient(redis_options); context.callbackWaitsForEmptyEventLoop = false; client.on('connect', () => { console.log('Connected:', client.connected); }); client.on('end', () => { console.log('Connection closed.'); });
https://riptutorial.com/zh-CN/home 30
client.on('ready', function () { console.log('Connection ready.'); client.keys('*', (err, keys) => { //always quit the redis client when no longer needed //else the connection will be used up client.quit(); const response = { statusCode: 200, body: keys, }; return callback(null, response); }); } catch (err) { if (client) { client.quit();} console.log('Error!: ' + err.message); callback(err); } };
S3AWS Lambda https://riptutorial.com/zh-CN/aws-lambda/topic/9286/s3aws-lambda
https://riptutorial.com/zh-CN/home 31
7:
AWS Lambda。。
“” https //serverless.com/
Examples
npm install serverless -g
Node.jsAWS Lamdba
serverless create --template aws-nodejs
handler.js
'use strict'; // Your first function handler module.exports.hello = (event, context, cb) => cb(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event } ); // You can add more handlers here, and reference them in serverless.yml
AWS
serverless deploy
CRUD
CRUD
npm install serverless -g
Lambda
serverless create --template aws-nodejs --path myService
myService
serverless.yml1. handler.js2. event.json3.
https://riptutorial.com/zh-CN/home 32
serverless.yml CRUD。
serverless.yml
service: serverless-crud provider: name: aws runtime: nodejs4.3 region: us-east-1 stage: dev iamRoleStatements: - Effect: Allow Action: - dynamodb:DescribeTable - dynamodb:Query - dynamodb:Scan - dynamodb:GetItem - dynamodb:PutItem - dynamodb:UpdateItem - dynamodb:DeleteItem Resource: "arn:aws:dynamodb:us-east-1:*:*" functions: create: handler: handler.create events: - http: path: todos method: post cors: true readAll: handler: handler.readAll events: - http: path: todos method: get cors: true readOne: handler: handler.readOne events: - http: path: todos/{id} method: get cors: true update: handler: handler.update events: - http: path: todos/{id} method: put cors: true delete: handler: handler.delete events: - http: path: todos/{id} method: delete cors: true
https://riptutorial.com/zh-CN/home 33
resources: Resources: TodosDynamoDbTable: Type: 'AWS::DynamoDB::Table' DeletionPolicy: Retain Properties: AttributeDefinitions: - AttributeName: id AttributeType: S KeySchema: - AttributeName: id KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 1 WriteCapacityUnits: 1 TableName: 'todos'
Lambda1. Lambda2. Dynamodb3. HTTPAPI4.
handler.jslambdanode.js。
'use strict'; const todosCreate = require('./todos-create.js'); const todosReadAll = require('./todos-read-all.js'); const todosReadOne = require('./todos-read-one.js'); const todosUpdate = require('./todos-update.js'); const todosDelete = require('./todos-delete.js'); module.exports.create = (event, context, callback) => { todosCreate(event, (error, result) => { const response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify(result), }; context.succeed(response); }); }; module.exports.readAll = (event, context, callback) => { todosReadAll(event, (error, result) => { const response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify(result),
https://riptutorial.com/zh-CN/home 34
}; context.succeed(response); }); }; module.exports.readOne = (event, context, callback) => { todosReadOne(event, (error, result) => { const response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify(result), }; context.succeed(response); }); }; module.exports.update = (event, context, callback) => { todosUpdate(event, (error, result) => { const response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify(result), }; context.succeed(response); }); }; module.exports.delete = (event, context, callback) => { todosDelete(event, (error, result) => { const response = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "*" }, body: JSON.stringify(result), }; context.succeed(response); }); };
CRUD
create.js1. -all.js2. - one.js3. update.js4. delete.js5.
。
https://riptutorial.com/zh-CN/home 35
todos-create.js
'use strict'; const AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient(); const uuid = require('uuid'); module.exports = (event, callback) => { const data = JSON.parse(event.body); data.id = uuid.v1(); data.updatedAt = new Date().getTime(); const params = { TableName: 'todos', Item: data }; return dynamoDb.put(params, (error, data) => { if (error) { callback(error); } callback(error, params.Item); }); };
todos-read-all.js
'use strict'; const AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient(); module.exports = (event, callback) => { const params = { TableName: 'todos', }; return dynamoDb.scan(params, (error, data) => { if (error) { callback(error); } callback(error, data.Items); }); }; For todos-read-one.js <br> 'use strict'; const AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient(); module.exports = (event, callback) => { const params = { TableName: 'todos', Key: {
https://riptutorial.com/zh-CN/home 36
id: event.pathParameters.id } }; return dynamoDb.get(params, (error, data) => { if (error) { callback(error); } callback(error, data.Item); }); };
todos-update.js
'use strict'; const AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient(); module.exports = (event, callback) => { const data = JSON.parse(event.body); data.id = event.pathParameters.id; data.updatedAt = new Date().getTime(); const params = { TableName : 'todos', Item: data }; return dynamoDb.put(params, (error, data) => { if (error) { callback(error); } callback(error, params.Item); }); };
todos-delete.js
'use strict'; const AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient(); module.exports = (event, callback) => { const params = { TableName : 'todos', Key: { id: event.pathParameters.id } }; return dynamoDb.delete(params, (error, data) => { if (error) { callback(error); } callback(error, params.Key); });
https://riptutorial.com/zh-CN/home 37
};
npm
npm init npm1. npm install aws-sdk --save install aws-sdk2. npm install uuid --save3.
cd myService
serverless deploy
api。
curl -X POST https://XXXX.execute-api.region.amazonaws.com/dev/todos --data '{ "body" : "Learn Serverless" }'
curl https://XXXX.execute-api.region.amazonaws.com/dev/todos
curl https://XXXX.execute-api.region.amazonaws.com/dev/todos/<id>
curl -X PUT https://XXXX.execute-api.region.amazonaws.com/dev/todos/<id> --data '{ "body" : "Understand Serverless" }'
`curl -X DELETE https://XXXX.execute-api.region.amazonaws.com/dev/todos/<id`>
https://riptutorial.com/zh-CN/aws-lambda/topic/6719/
https://riptutorial.com/zh-CN/home 38
8: S3aws-lambdaJSON•“”•
•
Records - > [] - > s3 - > bucket - > name S3
Records - > [] - > s3 - > object - > key 。
S3JSON Schema $.Records[0].s3.object.key 。s3://mybucket/path/file.txtpath/file.txt
PythonUTF-8 URL。ascii。URLUTF-8 - LambdaS3ASCII
"Records";Lambda。
“” - >“”Lambda。PUT。
AWS Lambda。
Examples
S3 PUT
{ "Records": [ { "eventVersion": "2.0", "eventTime": "1970-01-01T00:00:00.000Z", "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "s3": { "configurationId": "testConfigRule", "object": { "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901", "key": "HappyFace.jpg", "size": 1024 }, "bucket": { "arn": "arn:aws:s3:::mybucket", "name": "sourcebucket", "ownerIdentity": { "principalId": "EXAMPLE" } }, "s3SchemaVersion": "1.0" },
https://riptutorial.com/zh-CN/home 39
"responseElements": { "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH", "x-amz-request-id": "EXAMPLE123456789" }, "awsRegion": "us-east-1", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "eventSource": "aws:s3" } ] }
S3aws-lambda https://riptutorial.com/zh-CN/aws-lambda/topic/6618/s3aws-lambda
https://riptutorial.com/zh-CN/home 40
S. No
Contributors
1 aws-lambda Ahmed Abouhegaza, alatar, Community
2 Alexa-KIT Niroshan Ranapathi
3 AWS LambdaPython Nithin K Anil
4 AWS LambdaS3 Doug Schwartz
5 aws-lambdaC Taterhead
6 S3AWS Lambda Adonis Lee Villamor
7Alastair McCormack, Ashan, Eric Nord, Luc Boissaye, Niroshan Ranapathi
8 S3aws-lambda Alastair McCormack, Marshall Anschutz
https://riptutorial.com/zh-CN/home 41