我创建了简单的Lambda函数并将其上传到AWS Lambda.
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class Hello implements RequestHandler{ @Override public String handleRequest(String input, Context context) { String output = "Bonjour, " + input + "!"; return output; } } }
我想使用java类从其他项目调用此Lambda函数.我aws-java-sdk-lambda-1.10.22
用来调用这个函数.但我无法成功.
这是我的InvokeLambda类,它是一个单独的项目.
import java.nio.ByteBuffer; import java.nio.charset.Charset; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.lambda.AWSLambdaClient; import com.amazonaws.services.lambda.model.InvokeRequest; public class InvokeLambda { private static final Log logger = LogFactory.getLog(InvokeLambda.class); private static final String awsAccessKeyId = "XXXXXX"; private static final String awsSecretAccessKey = "YYYY"; private static final String regionName = "us-west-2"; private static final String functionName = "Hello"; private static Region region; private static AWSCredentials credentials; private static AWSLambdaClient lambdaClient; /** * The entry point into the AWS lambda function. */ public static void main(String... args) { credentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey); lambdaClient = (credentials == null) ? new AWSLambdaClient() : new AWSLambdaClient(credentials); //lambdaClient.configureRegion(Regions.US_WEST_2); region = Region.getRegion(Regions.fromName(regionName)); lambdaClient.setRegion(region); try { InvokeRequest invokeRequest = new InvokeRequest(); invokeRequest.setFunctionName(functionName); invokeRequest.setPayload("\" AWS Lambda\""); System.out.println(byteBufferToString( lambdaClient.invoke(invokeRequest).getPayload(), Charset.forName("UTF-8"))); } catch (Exception e) { logger.error(e.getMessage()); // System.out.println(e.getMessage()); } } public static String byteBufferToString(ByteBuffer buffer, Charset charset) { byte[] bytes; if (buffer.hasArray()) { bytes = buffer.array(); } else { bytes = new byte[buffer.remaining()]; buffer.get(bytes); } return new String(bytes, charset); } }
如何使用java调用lambda函数?
根据您的评论中的信息,您调用该函数的客户端代码很好.问题似乎与功能本身的配置有关.具体来说,AWS Lambda无法找到您指定的处理程序(com.aws.HelloLambda::handleRequest
),因为它与处理程序类(Hello
)的名称和包以及该类()中方法的名称不匹配handleRequest
.
您可以通过AWS控制台更新功能处理程序名称.选择您的函数,然后选择配置选项卡,然后选择Handler属性.
您可能想要将其更改com.aws.HelloLambda::handleRequest
为Hello::handleRequest
.
在从Java客户端测试函数之前,您可以直接通过控制台对其进行测试,这将有助于确保正确配置该函数.