Context

更新时间:
复制 MD 格式

When Function Compute invokes your function, it passes a Context object to the handler method. The context object gives you access to the request ID, invocation credentials, function metadata, execution environment information, and a built-in logger — without any additional configuration.

Context methods

The Context interface is defined in the com.aliyun.fc.runtime package and exposes the following methods:

  • getRequestId() — Returns the unique ID for this invocation. Record it to correlate logs and troubleshoot errors.

  • getExecutionCredentials() — Returns temporary credentials that Function Compute obtains by assuming your service-linked role. The credentials are valid for 36 hours and include an AccessKey ID, AccessKey secret, and security token.

  • getFunctionParam() — Returns metadata about the invoked function, including its name, handler, memory, and timeout period.

  • getLogger() — Returns the logger encapsulated by Function Compute for writing structured logs.

  • getService() — Returns information about the service associated with the function.

  • getRetryCount() — Returns the number of times this invocation has been retried.

Interface definition:

package com.aliyun.fc.runtime;

public interface Context {

    public String getRequestId();

    public Credentials getExecutionCredentials();

    public FunctionParam getFunctionParam();

    public FunctionComputeLogger getLogger();

    public Service getService();

    # public OpenTracing getTracing();

    public int getRetryCount();
}

Access OSS using temporary credentials

The following example uses temporary credentials from the context to upload an object to Object Storage Service (OSS). The full project is available on GitHub: java11-oss.

Prerequisites

Before you begin, ensure that you have:

  • An OSS bucket (the example uses my-bucket)

  • A service-linked role attached with the AliyunOSSFullAccess policy. Use AliyunFCDefaultRole if you haven't set up a custom role

Example

package example;

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

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.Credentials;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

public class App implements StreamRequestHandler {

    @Override
    public void handleRequest(
            InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

        // The bucket must exist before running this function.
        String bucketName = "my-bucket";
        // Use an internal endpoint to avoid cross-region data transfer fees.
        // This example uses the internal endpoint for the China (Hangzhou) region.
        String endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";

        // Get temporary credentials from the context.
        // These credentials are short-lived and scoped to your service-linked role —
        // no need to hardcode AccessKey pairs in your function code.
        Credentials creds = context.getExecutionCredentials();

        // Build an OSS client using the temporary credentials.
        OSS ossClient = new OSSClientBuilder().build(
            endpoint,
            creds.getAccessKeyId(),
            creds.getAccessKeySecret(),
            creds.getSecurityToken()
        );

        // Upload a byte array as an object.
        // Do not include the bucket name in the object path.
        byte[] content = "Hello FC".getBytes();
        ossClient.putObject(bucketName, "exampledir/exampleobject.txt", new ByteArrayInputStream(content));

        ossClient.shutdown();

        outputStream.write(new String("done").getBytes());
    }
}

The key pattern: call context.getExecutionCredentials() to get short-lived credentials, then pass the AccessKey ID, AccessKey secret, and security token directly to OSSClientBuilder. This avoids storing long-term credentials in your function code.

What's next