AWS Lambda学习1:Java编程方式调用Lambda函数
什么是 AWS Lambda?
AWS Lambda 是一项无服务器计算服务,可使您无需预配置或管理服务器即可运行代码。简单地说,Lambda其实是一个函数运行环境。借助 AWS Lambda,您可以为任何类型的应用程序或后端服务运行代码,并且不必进行任何管理。
如何调用 AWS Lambda 函数?
您可以使用 Lambda 控制台、Lambda API、AWS 开发工具包、AWS CLI 和 AWS 工具包直接调用 Lambda 函数。您还可以配置其他 AWS 服务以调用您的函数,或者可以配置 Lambda 以从流或队列中读取并调用您的函数。
首先,我们来创建一个简单的lambda函数,开发流程如下:
- 编写代码(maven开发)
(1)创建Maven项目,pom.xml 中添加如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lenovo</groupId>
<artifactId>lambda</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>lambda</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>1.11.520</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.520</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-lambda</artifactId>
<version>1.11.520</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-codebuild</artifactId>
<version>1.11.745</version>
</dependency>
<!-- <dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration> <createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
(2)编写主函数
package example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class HelloPojo implements RequestHandler<RequestClass, ResponseClass>{
public ResponseClass handleRequest(RequestClass request, Context context){
String greetingString = String.format("Hello %s, %s.", request.firstName, request.lastName);
return new ResponseClass(greetingString);
}
}
(3)编写输入类RequestClass
package example;
public class RequestClass {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public RequestClass(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public RequestClass() {
}
}
(4)编写输出类ResponseClass
package example;
public class ResponseClass {
String greetings;
public String getGreetings() {
return greetings;
}
public void setGreetings(String greetings) {
this.greetings = greetings;
}
public ResponseClass(String greetings) {
this.greetings = greetings;
}
public ResponseClass() {
}
}
2、将maven工程打成jar包(以eclipse为例说明)
(1)清理,工程点击右键 → run as → Maven clean
(2)打包,工程点击右键 → run as → Maven install
在target目录下获取生成的jar包:lambda-0.0.1-SNAPSHOT.jar
3、打开AWS Lambda服务控制台,创建lambda函数,上传jar包
(1)登录控制台选择lambda服务
(2)创建lambda函数
a. 名称随意;
b. 选择语言;
c. 选择或创建角色,角色要有lambda执行权限。
(3)上传jar包
注意处理程序命名规则:包.类::方法名(例如: example.HelloPojo::handleRequest)
(4)点击保存,保存lambda函数
4、点击测试,编写测试用例。
①通过控制台调用lambda函数
(1)点击配置测试事件,填写测试用例。(json格式,对应方法的参数)
{
"firstName": "Jim",
"lastName": "Green"
}
(2) 点击测试按钮,即可运行
②通过lambda API调用lambda函数
要通过java编程方式调用线上lambda函数的话,必须要有授权,需要AWS_ACCESS_KEY和AWS_SECRET_KEY。key获取方式有多种,下面介绍两种获取方式:
第一种,用Amazon IAM页面生成,点此链接
第二种,通过IAM控制台 创建授权账户
- 创建lambda developer用户;
- 创建成功后会生成秘钥;
- 为用户添加访问lambda的权限
获取到access_key和secret_key后即可对lambda函数进行调用
private static final String AWS_ACCESS_KEY = "*****&&&&&*****";
private static final String AWS_SECRET_KEY = "#####*****#####";
测试类Test02:
package demo;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.List;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;
import com.amazonaws.services.lambda.model.ListFunctionsResult;
import utils.FileUtil;
public class Test02 {
private static final String AWS_ACCESS_KEY = "*****&&&&&*****";
private static final String AWS_SECRET_KEY = "#####*****#####";
private static final String regionName = "ap-southeast-1";
private static AWSCredentials credentials;
private static AWSLambda lambdaClient;
private static void init() {
credentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
AWSLambdaClientBuilder lambdaBuilder = AWSLambdaClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials));
lambdaBuilder.setRegion(regionName);
lambdaClient = lambdaBuilder.build();
}
private static void getAllFunctions() {
ListFunctionsResult functionResult = lambdaClient.listFunctions();
List<FunctionConfiguration> functions = functionResult.getFunctions();
for (FunctionConfiguration function : functions) {
System.out.println("functionName = " + function.getFunctionName() + ",role = " + function.getRole());
}
}
private static void testHello() {
// 读取测试事件
String path = Test02.class.getResource("test01.txt").getPath();
String testEvent = FileUtil.getContent(path);
System.out.println("testEvent:" + testEvent);
try {
// 调用lambda函数
InvokeRequest request = new InvokeRequest().withFunctionName("test06").withLogType("Tail")
.withPayload(ByteBuffer.wrap(testEvent.getBytes()));
InvokeResult response = lambdaClient.invoke(request);
// 打印函数执行结果(把Ascii码转换成字符串)
ByteBuffer buffer = response.getPayload();
byte[] byteArr = buffer.array();
String executeResult = new String(byteArr);
System.out.println("executeResult:" + executeResult);
// 打印结果日志
String logResult = response.getLogResult();
String decodeText = new String(Base64.getDecoder().decode(logResult), "UTF-8");
System.out.println("logResult:");
System.out.println(decodeText);
// 打印返回的状态码
Integer code = response.getStatusCode();
System.out.println("statusCode:" + code.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String... args) {
init();
//getAllFunctions();
testHello();
}
}
FileUtil:
package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileUtil {
public static String getContent(String filePath) {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))));
String line = "";
while (true) {
line = br.readLine();
if (line == null) {
break;
}
sb.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public static void main(String[] args) {
String path = FileUtil.class.getResource("/demo/test01.txt").getPath();
try {
String fileContent = getContent(path);
System.out.println("fileContent = " + fileContent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
函数执行结果:
可以看到,两种调用方式执行结果一致。
参考文档:https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/welcome.html