This topic describes how to use the SDK for Java to manage stateful asynchronous invocations for functions.
SDK sample code
package com.mycompany.FcSample;
import com.aliyuncs.fc.client.FunctionComputeClient;
import com.aliyuncs.fc.request.*;
import com.aliyuncs.fc.response.*;
import com.aliyuncs.fc.constants.Const;
import com.aliyuncs.fc.model.*;
import java.io.IOException;
public class FcSample {
private static final String REGION = "cn-hangzhou";
public static void main(final String[] args) throws IOException {
String accessKey = System.getenv("ACCESS_KEY_ID");
String accessSecretKey = System.getenv("ACCESS_KEY_SECRET");
String accountId = System.getenv("ACCOUNT_ID");
// Initialize the client.
FunctionComputeClient fcClient = new FunctionComputeClient(REGION, accountId, accessKey, accessSecretKey);
// Specify the endpoint as needed, such as http://123456.cn-hangzhou.fc.aliyuncs.com.
// Specify the endpoint of the client in the format of http://{accountId}.{regionId}.fc.aliyuncs.com.
// Publish an asynchronous invocation configuration for a function.
AsyncConfig config = new AsyncConfig();
config.setStatefulInvocation(true);
String invocationID = "ivk-id";
String SERVICE_NAME = "";
String FUNCTION_NAME = "";
PutFunctionAsyncConfigRequest putFunctionAsyncConfigRequest = new PutFunctionAsyncConfigRequest(SERVICE_NAME, "", FUNCTION_NAME);
putFunctionAsyncConfigRequest.setAsyncConfig(config);
PutFunctionAsyncConfigResponse pResp = fcClient.putFunctionAsyncConfig(putFunctionAsyncConfigRequest);
// Asynchronously invoke the function.
// Take note of the request header passed in the setHeader() method. The setHeader() method is used to set the header metadata of the response.
InvokeFunctionRequest request = new InvokeFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
request.setHeader("x-fc-invocation-type", Const.INVOCATION_TYPE_ASYNC);
request.setStatefulAsyncInvocationId(invocationID);
InvokeFunctionResponse ivkResp = fcClient.invokeFunction(request);
// Query the information about a stateful asynchronous invocation.
GetStatefulAsyncInvocationRequest req = new GetStatefulAsyncInvocationRequest(SERVICE_NAME, "", FUNCTION_NAME, invocationID);
GetStatefulAsyncInvocationResponse resp = fcClient.getStatefulAsyncInvocation(req);
// Query stateful asynchronous invocations.
ListStatefulAsyncInvocationsRequest lReq = new ListStatefulAsyncInvocationsRequest(SERVICE_NAME, FUNCTION_NAME);
lReq.setInvocationIdPrefix("stateful-invocationId");
lReq.setIncludePayload(true);
lReq.setLimit(100);
ListStatefulAsyncInvocationsResponse lResp = fcClient.listStatefulAsyncInvocations(lReq);
// Terminate a stateful asynchronous invocation.
StopStatefulAsyncInvocationRequest sReq = new StopStatefulAsyncInvocationRequest(SERVICE_NAME, "", FUNCTION_NAME, invocationID);
StopStatefulAsyncInvocationResponse sResp = new StopStatefulAsyncInvocationResponse();
sResp = fcClient.stopStatefulAsyncInvocation(sReq);
}
}