Java 中 Azure 函数类的生命周期

问题描述 投票:0回答:1

我很难找到有关包含 Azure Functions 的 Java 类生命周期的任何信息。

每个函数执行是否都使用该类的新实例?我需要知道的原因是我想将执行上下文特定对象(例如 context.getLogger())保存到实例变量中以避免传递它们。

azure-functions
1个回答
0
投票

我同意 Paizo 的观点,在高负载的情况下,实例可能会被重用。

  • Azure Functions 尝试在多次调用时重用函数类的实例以优化性能。在这种情况下
    single instance of function class may handle multiple invocations
  • context.getLogger()
    特定于每个函数调用。对于不同的调用,将此对象存储为实例变量可能存在风险
    because the same instance of your function class might be reused
  • 您可以将此对象作为方法参数传递给特定方法,而不是将
    Logger
    等特定于执行上下文的对象保存为函数类中的实例变量,如下例所示:

功能代码:

public class TimerFunction {
    
    @FunctionName("TimerFunction")
    public void run(
        @TimerTrigger(name = "timerInfo", schedule = "0 */5 * * * *") String timerInfo,
        ExecutionContext context)
       {
        Logger logger = context.getLogger();

        // Your function logic here
        logger.info("Timer trigger function executed.");
       }
}
  • 如果您需要在函数类的方法中使用
    context.getLogger()
    ,请将
    Logger
    作为方法参数传递,如上面函数代码中所述。
© www.soinside.com 2019 - 2024. All rights reserved.