- Notifications
You must be signed in to change notification settings - Fork66
FaaS (Function as a service) framework for writing portable Java functions
License
GoogleCloudPlatform/functions-framework-java
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
An open source FaaS (Function as a service) framework for writing portableJava functions.
The Functions Framework lets you write lightweight functions that run in manydifferent environments, including:
- Google Cloud Run functions
- Your local development machine
- Knative-based environments
The Functions Framework for Java usesJava andMaven (themvn
command),for building and deploying functions from source.
However, it is also possible to build your functions usingGradle, as JAR archives, that you will deploy with thegcloud
command-line.
A function is typically structured as a Maven project. We recommend using an IDEthat supports Maven to create the Maven project. Add this dependency in thepom.xml
file of your project:
<dependency> <groupId>com.google.cloud.functions</groupId> <artifactId>functions-framework-api</artifactId> <version>1.1.2</version> <scope>provided</scope> </dependency>
If you are using Gradle to build your functions, you can define the FunctionsFramework dependency in yourbuild.gradle
project file as follows:
dependencies { implementation'com.google.cloud.functions:functions-framework-api:1.1.2' }
Create a filesrc/main/java/com/example/HelloWorld.java
with the followingcontents:
packagecom.example;importcom.google.cloud.functions.HttpFunction;importcom.google.cloud.functions.HttpRequest;importcom.google.cloud.functions.HttpResponse;publicclassHelloWorldimplementsHttpFunction {@Overridepublicvoidservice(HttpRequestrequest,HttpResponseresponse)throwsException {response.getWriter().write("Hello, World\n"); }}
There are two ways to write a Background function, which differ in how thepayload of the incoming event is represented. In a "raw" background functionthis payload is presented as a JSON-encoded Java string. In a "typed" backgroundfunction the Functions Framework deserializes the JSON payload into a Plain OldJava Object (POJO).
Create a filesrc/main/java/com/example/Background.java
with the followingcontents:
packagecom.example;importcom.google.cloud.functions.Context;importcom.google.cloud.functions.RawBackgroundFunction;importcom.google.gson.Gson;importcom.google.gson.JsonObject;importjava.util.logging.Logger;publicclassBackgroundimplementsRawBackgroundFunction {privatestaticfinalLoggerlogger =Logger.getLogger(Background.class.getName());@Overridepublicvoidaccept(Stringjson,Contextcontext) {Gsongson =newGson();JsonObjectjsonObject =gson.fromJson(json,JsonObject.class);logger.info("Received JSON object: " +jsonObject); }}
Create a filesrc/main/java/com/example/PubSubBackground
with the followingcontents:
packagecom.example;importcom.google.cloud.functions.BackgroundFunction;importcom.google.cloud.functions.Context;importjava.util.Map;importjava.util.logging.Logger;// This is the Pub/Sub message format from the Pub/Sub emulator.classPubSubMessage {Stringdata;Map<String,String>attributes;StringmessageId;StringpublishTime;}publicclassPubSubBackgroundimplementsBackgroundFunction<PubSubMessage> {privatestaticfinalLoggerlogger =Logger.getLogger(PubSubBackground.class.getName());@Overridepublicvoidaccept(PubSubMessagepubSubMessage,Contextcontext) {logger.info("Received message with id " +context.eventId()); }}
The Maven plugin calledfunction-maven-plugin
allows you to run functionson your development machine.
You can configure the plugin inpom.xml
:
<plugin> <groupId>com.google.cloud.functions</groupId> <artifactId>function-maven-plugin</artifactId> <version>0.10.1</version> <configuration> <functionTarget>com.example.HelloWorld</functionTarget> </configuration></plugin>
Then run it from the command line:
mvn function:run
You can alternatively configure the plugin with properties on the command line:
mvn com.google.cloud.functions:function-maven-plugin:0.10.1:run \ -Drun.functionTarget=com.example.HelloWorld
You can also run a function by using the Functions Framework jar directly.Copy the Functions Framework jar to a local location like this:
mvn dependency:copy \ -Dartifact='com.google.cloud.functions.invoker:java-function-invoker:1.3.2' \ -DoutputDirectory=.
In this example we use the current directory.
but you can specify any otherdirectory to copy to. Then run your function:
java -jar java-function-invoker-1.3.2 \ --classpath myfunction.jar \ --target com.example.HelloWorld
From Gradle, similarily to running functions with the Functions Framework jar,we can invoke theInvoker
class with aJavaExec
task.
configurations { invoker}dependencies { implementation'com.google.cloud.functions:functions-framework-api:1.1.2' invoker'com.google.cloud.functions.invoker:java-function-invoker:1.3.2'}tasks.register("runFunction",JavaExec) { main='com.google.cloud.functions.invoker.runner.Invoker' classpath(configurations.invoker) inputs.files(configurations.runtimeClasspath, sourceSets.main.output) args('--target', project.findProperty('run.functionTarget'),'--port', project.findProperty('run.port')?:8080 ) doFirst { args('--classpath', files(configurations.runtimeClasspath, sourceSets.main.output).asPath) }}
Then in your terminal or IDE, you will be able to run the function locally with:
gradle runFunction -Prun.functionTarget=com.example.HelloWorld \ -Prun.port=8080
Or if you use the Gradle wrapper provided by your Gradle project build:
./gradlew runFunction -Prun.functionTarget=com.example.HelloWorld \ -Prun.port=8080
There are a number of options that can be used to configure the FunctionsFramework, whether run directly or on the command line.
A function is a Java class. You must specify the name of that class when runningthe Functions Framework:
--target com.example.HelloWorld<functionTarget>com.example.HelloWorld</functionTarget>-Drun.functionTarget=com.example.HelloWorld-Prun.functionTarget=com.example.HelloWorld
- Invoker argument:
--target com.example.HelloWorld
- Maven
pom.xml
:<functionTarget>com.example.HelloWorld</functionTarget>
- Maven CLI argument:
-Drun.functionTarget=com.example.HelloWorld
- Gradle CLI argument:
-Prun.functionTarget=com.example.HelloWorld
The Functions Framework is an HTTP server that directs incoming HTTP requests tothe function code. By default this server listens on port 8080. Specify analternative value like this:
- Invoker argument:
--port 12345
- Maven
pom.xml
:<port>12345</port>
- Maven CLI argument:
-Drun.port=12345
- Gradle CLI argument:
-Prun.port=12345
Function code runs with a classpath that includes the function code itself andits dependencies. The Maven plugin automatically computes the classpath basedon the dependencies expressed inpom.xml
. When invoking the FunctionsFramework directly, you must use--classpath
to indicate how to find the codeand its dependencies. For example:
java -jar java-function-invoker-1.3.2 \ --classpath 'myfunction.jar:/some/directory:/some/library/*' \ --target com.example.HelloWorld
The--classpath
option works likejava -classpath
.It is a list of entries separated by:
(;
on Windows), where each entry is:
- a directory, in which case class
com.example.Foo
is looked for in a filecom/example/Foo.class
under that directory; - a jar file, in which case class
com.example.Foo
is looked for in a filecom/example/Foo.class
in that jar file; - a directory followed by
/*
(\*
on Windows), in which case each jar filein that directory (file calledfoo.jar
) is treated the same way as if ithad been named explicitly.
Specifying the right classpath can be tricky. A simpler alternative is tobuild the function as a "fat jar", where the function code and all itsdependencies are in a single jar file. Then--classpath myfatfunction.jar
is enough. An example of how this is done is the Functions Framework jar itself,as seenhere.
Alternatively, you can arrange for your jar to have its own classpath, asdescribedhere.
About
FaaS (Function as a service) framework for writing portable Java functions
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.