本文提供使用Java SDK配置函数有状态异步调用的示例代码。

SDK示例

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");

        // 初始化客户端。
        FunctionComputeClient fcClient = new FunctionComputeClient(REGION, accountId, accessKey, accessSecretKey);

        // 按需设置特定的接入点Endpoint,例如:http://123456.cn-hangzhou.fc.aliyuncs.com。
        // 设置函数客户端接入点Endpoint:http://{accountId}.{regionId}.fc.aliyuncs.com。

        // 发布异步配置。
        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);

        // 异步调用。
        // 需要重视通过setHeader传入的请求头,setHeader是用于设置返回页面的头meta信息。
        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);

        // 获取有状态异步调用。
        GetStatefulAsyncInvocationRequest req = new GetStatefulAsyncInvocationRequest(SERVICE_NAME, "", FUNCTION_NAME, invocationID);
        GetStatefulAsyncInvocationResponse resp = fcClient.getStatefulAsyncInvocation(req);
       
        // 列举有状态异步调用。
        ListStatefulAsyncInvocationsRequest lReq = new ListStatefulAsyncInvocationsRequest(SERVICE_NAME, FUNCTION_NAME);
        lReq.setInvocationIdPrefix("stateful-invocationId");
        lReq.setIncludePayload(true);
        lReq.setLimit(100);
        ListStatefulAsyncInvocationsResponse lResp = fcClient.listStatefulAsyncInvocations(lReq);

        // 停止有状态的异步调用。
        StopStatefulAsyncInvocationRequest sReq = new StopStatefulAsyncInvocationRequest(SERVICE_NAME, "", FUNCTION_NAME, invocationID);
        StopStatefulAsyncInvocationResponse sResp = new StopStatefulAsyncInvocationResponse();
        sResp = fcClient.stopStatefulAsyncInvocation(sReq);
    }
}