将 CreateFunction 与 Amazon SDK 或 CLI 配合使用 - Amazon CloudFront
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

CreateFunction 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示了如何使用 CreateFunction

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudfront.model.CloudFrontException; import software.amazon.awssdk.services.cloudfront.model.CreateFunctionRequest; import software.amazon.awssdk.services.cloudfront.model.CreateFunctionResponse; import software.amazon.awssdk.services.cloudfront.model.FunctionConfig; import software.amazon.awssdk.services.cloudfront.model.FunctionRuntime; import java.io.InputStream; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateFunction { public static void main(String[] args) { final String usage = """ Usage: <functionName> <filePath> Where: functionName - The name of the function to create.\s filePath - The path to a file that contains the application logic for the function.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String functionName = args[0]; String filePath = args[1]; CloudFrontClient cloudFrontClient = CloudFrontClient.builder() .region(Region.AWS_GLOBAL) .build(); String funArn = createNewFunction(cloudFrontClient, functionName, filePath); System.out.println("The function ARN is " + funArn); cloudFrontClient.close(); } public static String createNewFunction(CloudFrontClient cloudFrontClient, String functionName, String filePath) { try { InputStream fileIs = CreateFunction.class.getClassLoader().getResourceAsStream(filePath); SdkBytes functionCode = SdkBytes.fromInputStream(fileIs); FunctionConfig config = FunctionConfig.builder() .comment("Created by using the CloudFront Java API") .runtime(FunctionRuntime.CLOUDFRONT_JS_1_0) .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() .name(functionName) .functionCode(functionCode) .functionConfig(config) .build(); CreateFunctionResponse response = cloudFrontClient.createFunction(functionRequest); return response.functionSummary().functionMetadata().functionARN(); } catch (CloudFrontException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 CreateFunction

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 CloudFront 与 Amazon SDK 配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。