文档管理中心

Java

引入Java runtime SDK

SDK版本更新说明

展开

版本号

发布时间

更新说明

1.0.5.300

2022-09-30

首次发布Java runtime SDK。

通过Maven方式引入

  1. 在Maven配置文件,默认名称为settings.xml,或工程中的pom.xml文件中设置华为开发者联盟Maven仓库地址。
    收起
    自动换行
    深色代码主题
    复制
    1. <repositories>
    2. <repository>
    3. <id>developer_huawei</id>
    4. <url>https://developer.huawei.com/repo/</url>
    5. <releases>
    6. <enabled>true</enabled>
    7. </releases>
    8. <snapshots>
    9. <enabled>true</enabled>
    10. </snapshots>
    11. </repository>
    12. </repositories>
  2. 配置agc-function-java依赖。
    收起
    自动换行
    深色代码主题
    复制
    1. <dependency>
    2. <groupId>com.huawei.agconnect.server</groupId>
    3. <artifactId>agconnect-function-java</artifactId>
    4. <version>1.0.5.300</version>
    5. </dependency>

入口方法

入口方法定义如下:

收起
自动换行
深色代码主题
复制
  1. < T > handleRequest (I event, Context context) { ... }
  • < T >:方法返回数据对象,必须满足能转化为JSON字符串。
  • handleRequest:入口方法名称。
  • event:调用方传递的事件对象,JSON格式,可自定义。具体内容请参见event对象
  • context:函数运行时上下文对象,封装了日志接口context.getLogger()等。

完整的Java 1.8云函数示例代码请参考函数示例

日志记录

  • 记录日志接口:RunLog log=LogFactory.getRunLog()。

    使用示例:log.debug()。

  • 目前日志支持级别为INFO,WARN,DEBUG,ERROR。

获取环境变量

您可在代码中使用context.getClientContext().getEnvironments().get(key)访问环境变量,获取环境变量env1示例如下:
收起
自动换行
深色代码主题
复制
  1. String env1 = context.getClientContext().getEnvironments().get("env1");

若环境变量未配置,则会返回环境变量为null。

异常处理

示例代码如下:

收起
自动换行
深色代码主题
复制
  1. Map<String, String> result = new HashMap<>();
  2. try {
  3. RunLog log = LogFactory.getRunLog();
  4. log.info(JSONObject.toJSONString(request));
  5. result.put("message", "success");
  6. return result;
  7. } catch(Exception err) {
  8. Map<String, String> error = new HashMap<>();
  9. error.put("error", err.getMessage());
  10. return error;
  11. }

函数示例

示例代码如下:

说明

示例代码中入口方法handleRequest()的返回值类型仅供您参考,您可以根据实际需要定义。

收起
自动换行
深色代码主题
复制
  1. package faas;
  2. import com.alibaba.fastjson.JSONObject;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class HelloPojo {
  6. /**
  7. * Describe the basic method of Cloud Functions
  8. *
  9. * @param request
  10. * @param context
  11. * @return HTTP response
  12. */
  13. public CanonicalHttpTriggerResponse handleRequest(JSONObject request, Context context) {
  14. // example of display environment variables
  15. String env1 = context.getClientContext().getEnvironments().get("env1");
  16. // example of display logs
  17. RunLog log = LogFactory.getRunLog();
  18. log.info("Test info log");
  19. log.warn("Test warn log");
  20. log.debug("Test debug log");
  21. log.error("Test error log");
  22. log.info("----------Start-----------");
  23. JSONObject result = new JSONObject();
  24. result.put("code", 0);
  25. try {
  26. long interval;
  27. long startTime = System.currentTimeMillis();
  28. // print input parameters and environment variables
  29. String req = request.getString("request");
  30. log.info("request : " + req + ", env1 : " + env1);
  31. long endTime = System.currentTimeMillis();
  32. interval = endTime - startTime;
  33. log.info("intervalTime: " + interval + "(ms)");
  34. result.put("intervalTime: ", interval + "(ms)");
  35. log.info("--------Finished---------");
  36. } catch (Exception e) {
  37. log.error("the ex is " + e.getMessage());
  38. result.put("msg", e.getMessage());
  39. }
  40. Map<String, String> header = new HashMap<>();
  41. header.put("faas-content-type", "json");
  42. header.put("res-type", "context.env");
  43. CanonicalHttpTriggerResponse resp = new CanonicalHttpTriggerResponse.Builder()
  44. .withContentType("application/json")
  45. .withHeaders(header)
  46. .base64Flag(false)
  47. .withStatusCode(200)
  48. .build();
  49. resp.setBody(result.toJSONString());
  50. return resp;
  51. }
  52. }

pom.xml文件:

收起
自动换行
深色代码主题
复制
  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.78</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.huawei.agconnect.server</groupId>
  8. <artifactId>agconnect-function-java</artifactId>
  9. <version>1.0.5.300</version>
  10. </dependency>

准备函数部署包

函数部署包示例:java_demo.zip

Java函数部署包推荐结构如下所示,处理程序所在代码jar和依赖项放到lib文件夹,其他配置项放在config文件夹。

收起
自动换行
深色代码主题
复制
  1. function.zip
  2. |---config
  3. |---配置项
  4. |---lib
  5. |---依赖项 *.jar
  6. |---处理程序编译后的jar

可通过Maven工具管理Java项目依赖:

  1. 项目中增加zip_file.xml文件。

    注意
    • 建议您把项目的配置文件,比如认证凭据文件agc-apiclient-*.json,放置到resources目录下,通过脚本一起打包到函数部署包的config目录。
    • 若您要使用HelloPojo.class.getClassLoader().getResource("").getPath()获取resources目录下的文件路径,请按照以下示例步骤编写代码:
      收起
      自动换行
      深色代码主题
      复制
      1. // 1.获取resources路径
      2. String resourcePath = Test.class.getClassLoader().getResource("").getPath();
      3. // 2.通过字符串拼接的方式得到配置文件agc-apiclient-*.json的路径
      4. String filePath = resourcePath + "agc-apiclient-*.json";
    收起
    自动换行
    深色代码主题
    复制
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <assembly
    3. xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
    4. >
    5. <id>auto-deploy</id>
    6. <baseDirectory></baseDirectory>
    7. <formats>
    8. <format>zip</format>
    9. </formats>
    10. <!--配置统一打包到config目录-->
    11. <fileSets>
    12. <fileSet>
    13. <directory>src/main/resources/</directory>
    14. <outputDirectory>config</outputDirectory>
    15. <includes>
    16. <include>**</include>
    17. </includes>
    18. <fileMode>0600</fileMode>
    19. <directoryMode>0700</directoryMode>
    20. </fileSet>
    21. </fileSets>
    22. <dependencySets>
    23. <dependencySet>
    24. <outputDirectory>lib</outputDirectory>
    25. <scope>runtime</scope>
    26. </dependencySet>
    27. </dependencySets>
    28. </assembly>
  2. pom.xml文件添加如下内容,安装maven-assembly-plugin插件,从而根据zip_file.xml文件中的配置进行打包。
    收起
    自动换行
    深色代码主题
    复制
    1. <!--打包功能-->
    2. <build>
    3. <plugins>
    4. <plugin>
    5. <groupId>org.apache.maven.plugins</groupId>
    6. <artifactId>maven-assembly-plugin</artifactId>
    7. <version>2.2-beta-5</version>
    8. <configuration>
    9. <archive>
    10. <manifest>
    11. <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
    12. </manifest>
    13. </archive>
    14. <appendAssemblyId>false</appendAssemblyId>
    15. </configuration>
    16. <executions>
    17. <execution>
    18. <id>auto-deploy</id>
    19. <phase>package</phase>
    20. <goals>
    21. <goal>single</goal>
    22. </goals>
    23. <configuration>
    24. <descriptors>
    25. <descriptor>src/main/assembly/zip_file.xml</descriptor>
    26. </descriptors>
    27. <finalName>onlinetest</finalName>
    28. <outputDirectory>target</outputDirectory>
    29. <archiverConfig>
    30. <directoryMode>0700</directoryMode>
    31. <fileMode>0600</fileMode>
    32. <defaultDirectoryMode>0700</defaultDirectoryMode>
    33. </archiverConfig>
    34. </configuration>
    35. </execution>
    36. </executions>
    37. </plugin>
    38. </plugins>
    39. </build>
  3. 编译项目后,执行mvn package命令,生成可上传的部署zip包。

在 指南 中进行搜索
请输入您想要搜索的关键词