文档

函数实例生命周期回调方法

更新时间:
一键部署

本文介绍Java运行时实现函数实例生命周期回调的方法。

背景信息

当您实现并配置函数实例生命周期回调后,函数计算系统将在相关实例生命周期事件发生时调用对应的回调程序。当前PHP运行时支持Initializer和PreStop两种函数实例生命周期回调函数。更多信息,请参见函数实例生命周期

函数实例生命周期回调程序与正常调用请求计费规则一致,但其执行日志只能在函数日志实例日志高级日志中查询,调用请求列表不会展示回调程序日志。具体操作,请参见查询回调函数相关日志

回调方法签名

Initializer回调签名

初始化回调程序(Initializer回调)是在函数实例启动成功之后,运行请求处理程序(Handler)之前执行。函数计算保证在一个实例生命周期内,成功且只成功执行一次Initializer回调。例如您的Initializer回调第一次执行失败了,系统会重试,直到成功为止,然后再执行您的请求处理程序。因此,您在实现Initializer回调时,需要保证它被重复调用时的正确性。

Initializer回调只有一个context输入参数,使用方法同事件请求处理程序。

使用Initializer回调需要继承FunctionInitializer接口,并实现该接口的initialize方法,接口定义如下。

package com.aliyun.fc.runtime;

import java.io.IOException;

/**
 * This is the interface for the initialization operation
 */
public interface FunctionInitializer {

    /**
     * The interface to handle a function compute initialize request
     *
     * @param context The function compute initialize environment context object.
     * @throws IOException IOException during I/O handling
     */
    void initialize(Context context) throws IOException;
}

PreStop回调签名

预停止回调程序(PreStop回调)在函数实例销毁前执行,使用PreStop回调需要继承PreStopHandler接口,并实现该接口的preStop方法,接口定义如下。

package com.aliyun.fc.runtime;

import java.io.IOException;

/**
 * This is the interface for the preStop operation
 */
public interface PreStopHandler {

    /**
     * The interface to handle a function compute preStop request
     *
     * @param context The function compute preStop environment context object.
     * @throws IOException IOException during I/O handling
     */
    void preStop(Context context) throws IOException;
}

简单示例:流式事件请求处理程序

package example;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.fc.runtime.FunctionInitializer;
import com.aliyun.fc.runtime.PreStopHandler;

public class App implements StreamRequestHandler, FunctionInitializer, PreStopHandler {
    @Override
    public void initialize(Context context) throws IOException {
        context.getLogger().info("initialize start ...");
    }

    @Override
    public void handleRequest(
            InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        context.getLogger().info("handlerRequest ...");
        outputStream.write(new String("hello world\n").getBytes());
    }

    @Override
    public void preStop(Context context) throws IOException {
        context.getLogger().info("preStop start ...");
    }
}

配置生命周期回调函数

通过控制台配置

函数计算控制台FC函数配置中设置生命周期回调,回调格式为[包名].[类名]::[方法名]。示例如下:db_java_lifecycle

  • Initializer回调程序:设置为example.App::initialize,表示实现example包中App.java文件里的initialize方法。

  • PreStop回调程序:设置为example.App::preStop,表示实现example包中App.java文件里的preStop方法。

通过Serverless Devs配置

如果使用Serverless Devs工具,需要在s.yaml配置文件中添加Initializer 回调程序PreFreeze 回调程序PreStop 回调程序

  • Initializer回调配置

    function配置下添加instanceLifecycleConfig.initializer字段,包括handlertimeout两个字段。

  • PreStop回调配置

    function配置下添加instanceLifecycleConfig.preStop字段,包括handlertimeout两个字段。

具体的示例如下所示。

# ------------------------------------
#   官方手册: https://manual.serverless-devs.com/user-guide/aliyun/#fc3
#   常见小贴士: https://manual.serverless-devs.com/user-guide/tips/
#   有问题快来钉钉群问一下吧:33947367
# ------------------------------------
edition: 3.0.0
name: hello-world-app
access: "default"

vars: # 全局变量
  region: "cn-hangzhou"

resources:
  hello_world:
    component: fc3 
    actions:       
      pre-${regex('deploy|local')}: 
        - run: mvn package -DskipTests
          path: ./
    props:
      region: ${vars.region}              
      functionName: "start-java-1xqf"
      description: 'hello world by serverless devs'
      runtime: "java8"
      code: ./target/HelloFCJava-1.0-SNAPSHOT-jar-with-dependencies.jar
      handler: example.App::handleRequest
      memorySize: 128
      timeout: 10
      instanceLifecycleConfig:      # 扩展函数
        initializer:                # initializer函数
          handler: example.App::initialize
          timeout: 60     
        preStop:                    # PreStop函数
          handler: example.App::preStop  # 函数入口
          timeout: 60               # 超时时间
 

关于Serverless Devs的YAML配置规范,请参见Serverless Devs常用命令

查看实例生命周期回调函数日志

您可以通过函数日志功能查看回调函数日志。

  1. 登录函数计算控制台,在左侧导航栏,单击函数

  2. 在顶部菜单栏,选择地域,然后在函数页面,单击目标函数。

  3. 在函数详情页面,选择测试页签,单击测试函数,然后选择日志 > 函数日志

    函数日志页签,您可以查看函数的调用日志和Initializer回调日志,示例如下。

    2023-09-06 11:18:10FC Initialize Start RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7
    2023-09-06 11:18:10load code for handler:index.initialize
    2023-09-06 11:18:102023-09-06 11:18:10 1-64f7ef72-64caf1ff0046194d9a26bbd7 [verbose] initializer
    2023-09-06 11:18:10FC Initialize End RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7
    2023-09-06 11:18:10FC Invoke Start RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7
    2023-09-06 11:18:10load code for handler:index.handler
    2023-09-06 11:18:10FC Invoke End RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7

    因为每个函数实例会缓存一段时间,不会马上销毁,因此不能立即查看PreStop回调日志。如需快速触发PreStop回调,可更新函数配置或者函数代码。更新完成后,再次查看函数日志,您可以查看PreStop回调日志。示例如下。

    2023-09-06 11:08:10FC PreStop Start RequestId: 944bca62-b209-47a1-9e48-2723647bce0a
    2023-09-06 11:08:10load code for handler:index.preStop
    2023-09-06 11:08:102023-09-06 11:08:10 944bca62-b209-47a1-9e48-2723647bce0a [verbose] preStop
    2023-09-06 11:08:10FC PreStop End RequestId: 944bca62-b209-47a1-9e48-2723647bce0a

示例程序

  • java11-mysql函数计算提供的Initializer回调和PreStop回调的示例程序。

    该示例为您展示了如何使用Java运行时的Initializer回调从环境变量中获取数据库配置并创建MySQL连接,以及如何使用PreStop回调负责关闭MySQL连接。

  • 本页导读 (1)
文档反馈