cheatsheet
用于 javascript 的 AWS-SDK
Lambda 在其全局中包含 aws-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.');
});
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);
}
};