Package com.google.cloud.functions
Interface RawBackgroundFunction
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
@FunctionalInterface public interface RawBackgroundFunction
Represents a Cloud Function that is activated by an event. The payload of the event is a JSON
object, which can be parsed using a JSON package such as
GSON.
Here is an example of an implementation that parses the JSON payload using Gson, to access its
messageId
property:
public class Example implements RawBackgroundFunction {
private static final Logger logger = Logger.getLogger(Example.class.getName());
@Override
public void accept(String json, Context context) {
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonElement messageId = jsonObject.get("messageId");
String messageIdString = messageId.getAsJsonString();
logger.info("Got messageId " + messageIdString);
}
}
Here is an example of an implementation that deserializes the JSON payload into a Java object for simpler access, again using Gson:
public class Example implements RawBackgroundFunction { private static final Logger logger = Logger.getLogger(Example.class.getName());@Override
public void accept(String json, Context context) { PubSubMessage message = new Gson().fromJson(json, PubSubMessage.class); logger.info("Got messageId " + message.messageId); } } // Where PubSubMessage is a user-defined class like this: public class PubSubMessage { String data;Map<String, String>
attributes; String messageId; String publishTime; }
-
Method Summary
-
Method Details
-
accept
Called to service an incoming event. This interface is implemented by user code to provide the action for a given background function. If this method throws any exception (including anyError
) then the HTTP response will have a 500 status code.- Parameters:
json
- the payload of the event, as a JSON string.context
- the context of the event. This is a set of values that every event has, separately from the payload, such as timestamp and event type.- Throws:
java.lang.Exception
- to produce a 500 status code in the HTTP response.
-