首页 函数计算(旧版) 操作指南 代码开发 C# 函数实例生命周期回调方法

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

更新时间: 2024-02-05 15:33:17

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

背景信息

当您实现并配置函数实例生命周期回调后,函数计算将在相关实例生命周期事件发生时调用对应的回调程序。函数实例生命周期涉及Initializer、PreStop和PreFreeze三种回调,C#运行时已支持此三种回调。更多信息,请参见函数实例生命周期

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

回调方法签名

  • 初始化回调程序(Initializer回调)

    在函数实例启动成功之后,运行请求处理程序(Handler)之前执行。函数计算保证在一个实例生命周期内,成功且只成功执行一次Initializer回调。如果您的Initializer回调第一次执行失败,那么此次函数调用直接返回失败,下次调用时,会再新建一个函数实例执行Initializer回调。

  • 预冻结回调程序(PreFreeze回调)

    在函数实例冻结前执行。

  • 预停止回调程序(PreStop回调)

    在函数实例销毁前执行。

C#的Initializer回调、PreFreeze回调和PreStop回调方法签名相同,均只有一个Context输入参数,没有返回参数。定义如下。

public void FunctionName(IFcContext context);

您也可以将回调方法设置为静态方法,定义如下。

public static void FunctionName(IFcContext context);

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

以下示例代码展示一个简单的包含Initializer回调、PreFreeze回调和PreStop回调的程序。

using System;
using System.IO;
using System.Threading.Tasks;
using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;

namespace Example
{
    public class Hello
    {
        public void Initialize(IFcContext context)
        {
            IFcLogger logger = context.Logger;
            logger.LogInformation("Initialize start");
            logger.LogInformation("Handle initializer: {0}", context.RequestId);
            logger.LogInformation("Initialize end");
        }

        public void PreStop(IFcContext context)
        {
            IFcLogger logger = context.Logger;
            logger.LogInformation("PreStop start");
            logger.LogInformation("Handle PreStop: {0}", context.RequestId);
            logger.LogInformation("PreStop end");
        }

        public void PreFreeze(IFcContext context)
        {
            IFcLogger logger = context.Logger;
            logger.LogInformation("PreFreeze start");
            logger.LogInformation("Handle PreFreeze: {0}", context.RequestId);
            logger.LogInformation("PreFreeze end");
        }

        public async Task<Stream> StreamHandler(Stream input, IFcContext context)
        {
            IFcLogger logger = context.Logger;
            logger.LogInformation("Handle request: {0}", context.RequestId);

            MemoryStream copy = new MemoryStream();
            await input.CopyToAsync(copy);
            copy.Seek(0, SeekOrigin.Begin);
            return copy;
        }

        static void Main(string[] args){}
    }
}

配置生命周期回调函数

通过控制台配置

函数计算控制台的函数配置中设置生命周期回调,具体操作,请参见函数实例生命周期。回调方法的格式和请求处理程序的格式相同,为程序集名称::命名空间.类名::方法名。更多信息,请参见请求处理程序(Handler)

示例如下。

  • Initializer回调程序:HelloFcApp::Example.Hello::Initialize

  • PreFreeze回调程序:HelloFcApp::Example.Hello::PreFreeze

  • PreStop回调程序:HelloFcApp::Example.Hello::PreStop

通过Serverless Devs配置

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

  • Initializer回调配置

    function配置下添加initializerinitializationTimeout两个字段。

  • PreFreeze回调配置

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

  • PreStop回调配置

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

具体示例如下所示。

edition: 1.0.0
name: hello-world  #  项目名称
access: default    #  密钥别名

vars: # 全局变量
  region: cn-shanghai # 地域
  service:
    name: fc-example
    description: 'fc example by serverless devs'

services:
  helloworld: # 业务名称/模块名称
    component: fc
    actions: # 自定义执行逻辑
      pre-deploy: # 在deploy之前运行
        - run: mvn package # 要运行的命令行
          path: ./ # 命令行运行的路径
    props: #  组件的属性值
      region: ${vars.region}
      service: ${vars.service}
      function:
        name: dotnet-lifecycle-hook-demo
        description: 'fc example by serverless devs'
        runtime: dotnetcore3.1
        codeUri: ./target
        handler: example.App::handleRequest
        memorySize: 128
        timeout: 60
        initializer: HelloFcApp::Example.Hello::Initialize
        initializationTimeout: 30
        instanceLifecycleConfig:
          preStop:
            Handler: HelloFcApp::Example.Hello::PreStop
            Timeout: 30
          preFreeze:
            Handler: HelloFcApp::Example.Hello::PreFreeze
            Timeout: 30

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

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

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

  1. 登录函数计算控制台,在左侧导航栏,单击服务及函数
  2. 在顶部菜单栏,选择地域,然后在服务列表页面,单击目标服务。
  3. 函数管理页面,单击目标函数名称,然后在函数详情页面,单击测试函数页签。
  4. 测试函数页签,单击测试函数,然后选择调用日志 > 函数日志
    函数日志页签,您可以查看函数的调用日志、Initializer回调日志和PreFreeze回调日志,示例如下。
    2022-10-09 19:26:17 FunctionCompute dotnetcore3.1 runtime inited.
    2022-10-09 19:26:17 FC Initialize Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Initialize start
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle initializer: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Initialize end
    2022-10-09 19:26:17 FC Initialize End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC Invoke Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle request: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC Invoke End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC PreFreeze Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] PreFreeze start
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle PreFreeze: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] PreFreeze end
    2022-10-09 19:26:17 FC PreFreeze End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    因为每个函数实例会缓存一段时间,不会马上销毁,因此不能立即查看PreStop回调日志。如需快速触发PreStop回调,可更新函数配置或者函数代码。更新完成后,再次查看函数日志,您可以查看PreStop回调日志。示例如下。
    2022-10-09 19:32:17 FC PreStop Start RequestId: 03be685c-378b-4736-8b08-a67c1d*****
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] PreStop start
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] Handle PreStop: 03be685c-378b-4736-8b08-a67c1d*****
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] PreStop end
    2022-10-09 19:32:17 FC PreStop End RequestId: 03be685c-378b-4736-8b08-a67c1d*****
阿里云首页 函数计算(旧版) 相关技术圈