Function instance lifecycle hook methods
Implement the Initializer and PreStop hooks in the Java runtime to run setup and cleanup code when an instance starts or is destroyed.
Background information
After you implement and configure function instance lifecycle hooks, the Function Compute system calls the corresponding hook when a related instance lifecycle event occurs. The Java runtime supports two types of function instance lifecycle hooks: Initializer and PreStop. For more information, see Configure instance lifecycles.
Function instance lifecycle hooks follow the same billing rules as normal invocation requests. Their execution logs can be queried only in Real-time Logs, Function Logs, or Advanced Logs. The Requests List does not display hook logs. For details, see View the logs of instance lifecycle hooks.
Hook method signatures
Initializer hook signature
The Initializer hook runs after the function instance starts successfully and before the request handler (Handler) runs. Function Compute guarantees that the Initializer hook runs successfully exactly once within a single instance lifetime. If the first execution of your Initializer hook fails, that function invocation returns a failure immediately, and the next invocation creates a new function instance to run the Initializer hook.
When the Initializer hook times out or fails, the server always returns the HTTP 200 status code. You must use the response header X-Fc-Error-Type:InitializationError or the errorMessage field in the response body to determine whether the error is caused by an initialization failure.
The Initializer hook has only one input parameter, context, which is used in the same way as in Handler.
To use the Initializer hook, implement the FunctionInitializer interface and override its initialize method. The interface is defined as follows:
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 hook signature
The PreStop hook runs before the function instance is destroyed. To use the PreStop hook, implement the PreStopHandler interface and override its preStop method. The interface is defined as follows:
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;
}
Simple example: streaming event handler
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 ...");
}
}
InputStream supports streaming, but OutputStream does not support returning data as a stream.
Configure lifecycle hooks
Configure in the console
In Function Compute console, go to the FC function page and choose to configure the lifecycle hook. The hook format is [Package name].[Class name]::[Method name].
-
Initializer hook: set to
example.App::initialize, which means that the App.java file in theexamplepackage implements theinitializemethod. -
PreStop hook: set to
example.App::preStop, which means that the App.java file in theexamplepackage implements thepreStopmethod.
Configure by using Serverless Devs
If you use Serverless Devs, add the Initializer hook and the PreStop hook to the s.yaml configuration file.
-
Initializer hook configuration
Under the function configuration, add the instanceLifecycleConfig.initializer field, which includes two fields: handler and timeout.
-
PreStop hook configuration
Under the function configuration, add the instanceLifecycleConfig.preStop field, which includes two fields: handler and timeout.
A specific example is shown below.
# ------------------------------------
# Official manual: https://manual.serverless-devs.com/user-guide/aliyun/#fc3
# Common tips: https://manual.serverless-devs.com/user-guide/tips/
# If you have questions, ask in the DingTalk group: 33947367
# ------------------------------------
edition: 3.0.0
name: hello-world-app
access: "default"
vars: # Global variables
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: # Extension function
initializer: # initializer function
handler: example.App::initialize
timeout: 60
preStop: # PreStop function
handler: example.App::preStop # Function entry point
timeout: 60 # Timeout period
For details about the Serverless Devs YAML configuration specification, see Common Serverless Devs commands.
View the logs of instance lifecycle hooks
You can view the logs for lifecycle hook in Logs.
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Test Function tab, click Test Function, and then choose .
On the Logs tab, you can view function invocation logs and Initializer logs. Example:
2024-03-04 17:57:28FC Initialize Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69 2024-03-04 17:57:282024-03-04 09:57:28.192 1-65e59b07-1520da26-bf73bbb91b69 [info] initializer 2024-03-04 17:57:28FC Initialize End RequestId: 1-65e59b07-1520da26-bf73bbb91b69 2024-03-04 17:57:28FC Invoke Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69 2024-03-04 17:57:28FC Invoke End RequestId: 1-65e59b07-1520da26-bf73bbb91b69Each function instance is cached for a period of time and not immediately destroyed, you cannot view logs for PreStop hooks right away. To quickly trigger a PreStop hook, you can update the function configurations or function code. After the update is complete, you can view the logs for PreStop hooks in Function Logs. The following sample code shows an example:
2024-03-04 18:33:26FC PreStop Start RequestId: 93c93603-9fbe-4576-9458-193c8b213031 2024-03-04 18:33:262024-03-04 10:33:26.077 93c93603-9fbe-4576-9458-193c8b213031 [info] preStop 2024-03-04 18:33:26FC PreStop End RequestId: 93c93603-9fbe-4576-9458-193c8b213031
Example programs
-
java11-mysql: an example program provided by Function Compute for the Initializer hook and the PreStop hook.
This example shows how to use the Initializer hook in the Java runtime to get the database configuration from environment variables and create a MySQL connection. It also shows how to use the PreStop hook to close the MySQL connection.