Updated on 2023-07-24 GMT+08:00

Java Template

Stateful function:

// funcName: javastateful
import com.huawei.function.Function;
import com.huawei.function.runtime.StateReader;
import com.huawei.services.runtime.Context;

public class JavaHandler implements StateReader<Object, Counter> {
    public Object handleRequest(event Object, Context context) {
        // process req
        State state = (State)context.getState();
        // process state
        state.count++;
        context.setState(state);
        // function object
        Function func = new Function(context);
        // persistent state
        func.saveState();
        return state;
    }

    // Stateful functions must implement an initialization API.
    public State initState(Object event, Context context) {
        State state = new State(0);
        // Set state for initialization.
        context.setState(state);
        return state;
    }
}

class State {
    int count;
    State(int cnt) {
        this.counter = cnt;
	}
}

Invoking function:

// funcName: javacaller
import com.google.gson.JsonObject;
import com.huawei.function.Function;
import com.huawei.function.runtime.StateReader;
import com.huawei.services.runtime.Context;
import com.huawei.function.ObjectRef;

public class JavaHandler {
    // Initialization. Specify "new Function instanceName" as "test 1" to initialize the state route of function javastateful.
    public String newStateRouter(Object event, Context context) {
        Function func = new Function(context, "javastateful", "test1");
        String instanceID = func.getInstanceID();
        return instanceID;
    }

    // Bind the created state route.
    public String bindStateRouter(Object event, Context context) {
        Function func = new Function(context);
        // bind
        func.getInstance("javastateful", "test1");
        String instanceID = func.getInstanceID();
        return instanceID;
    }

    // Invoke after binding the route.
    public Object invoke(Object event, Context context) {
        Function func = new Function(context);
        // bind
        func.getInstance("javastateful", "test1");
        ObjectRef<Object> obj = func.invoke("{\"key\":\"value\"}");
        // Obtain the execution result.
        Object result = obj.get();
        return result;
    }

    // Delete the state instance.
    public Object terminate(Object event, Context context) {
        Function func = new Function(context);
        // bind
        func.getInstance("javastateful", "test1");
        ObjectRef<Object> obj = func.terminate();
        // Obtain the execution result.
        Object result = obj.get();
        return result;
    }
}