• Stars
    star
    135
  • Rank 269,297 (Top 6 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 5 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

FaaS (Function as a service) framework for writing portable Java functions

Functions Framework for Java

Maven Central (functions-framework-api) Maven Central (java-function-invoker) Maven Central (function-maven-plugin)

Java Unit CI Java Lint CI Java Conformance CI Security Scorecard

An open source FaaS (Function as a service) framework for writing portable Java functions -- brought to you by the Google Cloud Functions team.

The Functions Framework lets you write lightweight functions that run in many different environments, including:

Installation

The Functions Framework for Java uses Java and Maven (the mvn command), for building and deploying functions from source.

However, it is also possible to build your functions using Gradle, as JAR archives, that you will deploy with the gcloud command-line.

Quickstart: Hello, World on your local machine

A function is typically structured as a Maven project. We recommend using an IDE that supports Maven to create the Maven project. Add this dependency in the pom.xml file of your project:

    <dependency>
      <groupId>com.google.cloud.functions</groupId>
      <artifactId>functions-framework-api</artifactId>
      <version>1.0.4</version>
      <scope>provided</scope>
    </dependency>

If you are using Gradle to build your functions, you can define the Functions Framework dependency in your build.gradle project file as follows:

    dependencies {
        implementation 'com.google.cloud.functions:functions-framework-api:1.0.4'
    }

Writing an HTTP function

Create a file src/main/java/com/example/HelloWorld.java with the following contents:

package com.example;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;

public class HelloWorld implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws Exception {
    response.getWriter().write("Hello, World\n");
  }
}

Quickstart: Create a Background Function

There are two ways to write a Background function, which differ in how the payload of the incoming event is represented. In a "raw" background function this payload is presented as a JSON-encoded Java string. In a "typed" background function the Functions Framework deserializes the JSON payload into a Plain Old Java Object (POJO).

Writing a Raw Background Function

Create a file src/main/java/com/example/Background.java with the following contents:

package com.example;

import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.logging.Logger;

public class Background implements RawBackgroundFunction {
  private static final Logger logger =
      Logger.getLogger(Background.class.getName());

  @Override
  public void accept(String json, Context context) {
    Gson gson = new Gson();
    JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
    logger.info("Received JSON object: " + jsonObject);
  }
}

Writing a Typed Background Function

Create a file src/main/java/com/example/PubSubBackground with the following contents:

package com.example;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import java.util.Map;
import java.util.logging.Logger;

// This is the Pub/Sub message format from the Pub/Sub emulator. 
class PubSubMessage {
  String data;
  Map<String, String> attributes;
  String messageId;
  String publishTime;
}

public class PubSubBackground implements BackgroundFunction<PubSubMessage> {
  private static final Logger logger =
      Logger.getLogger(PubSubBackground.class.getName());

  @Override
  public void accept(PubSubMessage pubSubMessage, Context context) {
    logger.info("Received message with id " + context.eventId());
  }
}

Running a function with the Maven plugin

The Maven plugin called function-maven-plugin allows you to run functions on your development machine.

Configuration in pom.xml

You can configure the plugin in pom.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

Configuration on the command line

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

Running the Functions Framework directly

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.1.1' \
    -DoutputDirectory=.

In this example we use the current directory . but you can specify any other directory to copy to. Then run your function:

java -jar java-function-invoker-1.1.1 \
    --classpath myfunction.jar \
    --target com.example.HelloWorld

Running a function with Gradle

From Gradle, similarily to running functions with the Functions Framework jar, we can invoke the Invoker class with a JavaExec task.

Configuration in build.gradle

configurations {
    invoker
}

dependencies {
    implementation 'com.google.cloud.functions:functions-framework-api:1.0.4'
    invoker 'com.google.cloud.functions.invoker:java-function-invoker:1.1.1'
}

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

Functions Framework configuration

There are a number of options that can be used to configure the Functions Framework, whether run directly or on the command line.

Which function to run

A function is a Java class. You must specify the name of that class when running the 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

Which port to listen on

The Functions Framework is an HTTP server that directs incoming HTTP requests to the function code. By default this server listens on port 8080. Specify an alternative 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 classpath

Function code runs with a classpath that includes the function code itself and its dependencies. The Maven plugin automatically computes the classpath based on the dependencies expressed in pom.xml. When invoking the Functions Framework directly, you must use --classpath to indicate how to find the code and its dependencies. For example:

java -jar java-function-invoker-1.1.1 \
    --classpath 'myfunction.jar:/some/directory:/some/library/*' \
    --target com.example.HelloWorld

The --classpath option works like java -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 file com/example/Foo.class under that directory;
  • a jar file, in which case class com.example.Foo is looked for in a file com/example/Foo.class in that jar file;
  • a directory followed by /* (\* on Windows), in which case each jar file in that directory (file called foo.jar) is treated the same way as if it had been named explicitly.

Simplifying the classpath

Specifying the right classpath can be tricky. A simpler alternative is to build the function as a "fat jar", where the function code and all its dependencies 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 seen here.

Alternatively, you can arrange for your jar to have its own classpath, as described here.

More Repositories

1

microservices-demo

Sample cloud-first application with 10 microservices showcasing Kubernetes, Istio, and gRPC.
Go
16,790
star
2

terraformer

CLI tool to generate terraform files from existing infrastructure (reverse Terraform). Infrastructure to Code
Go
12,352
star
3

training-data-analyst

Labs and demos for courses for GCP Training (http://cloud.google.com/training).
Jupyter Notebook
7,867
star
4

python-docs-samples

Code samples used on cloud.google.com
Jupyter Notebook
7,432
star
5

generative-ai

Sample code and notebooks for Generative AI on Google Cloud, with Gemini on Vertex AI
Jupyter Notebook
6,517
star
6

golang-samples

Sample apps and code written for Google Cloud in the Go programming language.
Go
4,284
star
7

professional-services

Common solutions and tools developed by Google Cloud's Professional Services team. This repository and its contents are not an officially supported Google product.
Python
2,825
star
8

nodejs-docs-samples

Node.js samples for Google Cloud Platform products.
JavaScript
2,807
star
9

tensorflow-without-a-phd

A crash course in six episodes for software developers who want to become machine learning practitioners.
Jupyter Notebook
2,772
star
10

gcsfuse

A user-space file system for interacting with Google Cloud Storage
Go
2,046
star
11

community

Java
1,919
star
12

PerfKitBenchmarker

PerfKit Benchmarker (PKB) contains a set of benchmarks to measure and compare cloud offerings. The benchmarks use default settings to reflect what most users will see. PerfKit Benchmarker is licensed under the Apache 2 license terms. Please make sure to read, understand and agree to the terms of the LICENSE and CONTRIBUTING files before proceeding.
Python
1,885
star
13

asl-ml-immersion

This repos contains notebooks for the Advanced Solutions Lab: ML Immersion
Jupyter Notebook
1,799
star
14

vertex-ai-samples

Notebooks, code samples, sample apps, and other resources that demonstrate how to use, develop and manage machine learning and generative AI workflows using Google Cloud Vertex AI.
Jupyter Notebook
1,659
star
15

java-docs-samples

Java and Kotlin Code samples used on cloud.google.com
Java
1,610
star
16

ml-design-patterns

Source code accompanying O'Reilly book: Machine Learning Design Patterns
Jupyter Notebook
1,600
star
17

continuous-deployment-on-kubernetes

Get up and running with Jenkins on Google Kubernetes Engine
Shell
1,582
star
18

cloudml-samples

Cloud ML Engine repo. Please visit the new Vertex AI samples repo at https://github.com/GoogleCloudPlatform/vertex-ai-samples
Python
1,516
star
19

cloud-foundation-fabric

End-to-end modular samples and landing zones toolkit for Terraform on GCP.
HCL
1,509
star
20

localllm

Python
1,505
star
21

cloud-builders

Builder images and examples commonly used for Google Cloud Build
Go
1,374
star
22

cloud-sql-proxy

A utility for connecting securely to your Cloud SQL instances
Go
1,263
star
23

cloud-builders-community

Community-contributed images for Google Cloud Build
Go
1,258
star
24

berglas

A tool for managing secrets on Google Cloud
Go
1,236
star
25

data-science-on-gcp

Source code accompanying book: Data Science on the Google Cloud Platform, Valliappa Lakshmanan, O'Reilly 2017
Jupyter Notebook
1,230
star
26

kubernetes-engine-samples

Sample applications for Google Kubernetes Engine (GKE)
HCL
1,228
star
27

functions-framework-nodejs

FaaS (Function as a service) framework for writing portable Node.js functions
TypeScript
1,162
star
28

DataflowTemplates

Cloud Dataflow Google-provided templates for solving in-Cloud data tasks
Java
1,135
star
29

bigquery-utils

Useful scripts, udfs, views, and other utilities for migration and data warehouse operations in BigQuery.
Java
1,117
star
30

cloud-vision

Sample code for Google Cloud Vision
Python
1,097
star
31

bank-of-anthos

Retail banking sample application showcasing Kubernetes and Google Cloud
Java
994
star
32

buildpacks

Builders and buildpacks designed to run on Google Cloud's container platforms
Go
982
star
33

php-docs-samples

A collection of samples that demonstrate how to call Google Cloud services from PHP.
PHP
961
star
34

cloud-foundation-toolkit

The Cloud Foundation toolkit provides GCP best practices as code.
Go
958
star
35

deploymentmanager-samples

Deployment Manager samples and templates.
Jinja
938
star
36

flask-talisman

HTTP security headers for Flask
Python
896
star
37

k8s-config-connector

GCP Config Connector, a Kubernetes add-on for managing GCP resources
Go
891
star
38

gsutil

A command line tool for interacting with cloud storage services.
Python
874
star
39

DataflowJavaSDK

Google Cloud Dataflow provides a simple, powerful model for building both batch and streaming parallel data processing pipelines.
857
star
40

nodejs-getting-started

A tutorial for creating a complete application using Node.js on Google Cloud Platform
JavaScript
806
star
41

magic-modules

Add Google Cloud Platform support to Terraform
Go
804
star
42

gcr-cleaner

Delete untagged image refs in Google Container Registry or Artifact Registry
Go
802
star
43

keras-idiomatic-programmer

Books, Presentations, Workshops, Notebook Labs, and Model Zoo for Software Engineers and Data Scientists wanting to learn the TF.Keras Machine Learning framework
Jupyter Notebook
797
star
44

metacontroller

Lightweight Kubernetes controllers as a service
Go
790
star
45

awesome-google-cloud

A curated list of awesome stuff for Google Cloud.
777
star
46

mlops-on-gcp

Jupyter Notebook
773
star
47

getting-started-python

Code samples for using Python on Google Cloud Platform
Python
756
star
48

dotnet-docs-samples

.NET code samples used on https://cloud.google.com
C#
736
star
49

click-to-deploy

Source for Google Click to Deploy solutions listed on Google Cloud Marketplace.
Python
729
star
50

iap-desktop

IAP Desktop is a Windows application that provides zero-trust Remote Desktop and SSH access to Linux and Windows VMs on Google Cloud.
C#
708
star
51

cloud-sdk-docker

Google Cloud CLI Docker Image - Docker Image containing the gcloud CLI and its bundled components.
Dockerfile
697
star
52

tf-estimator-tutorials

This repository includes tutorials on how to use the TensorFlow estimator APIs to perform various ML tasks, in a systematic and standardised way
Jupyter Notebook
671
star
53

functions-framework-python

FaaS (Function as a service) framework for writing portable Python functions
Python
670
star
54

flink-on-k8s-operator

[DEPRECATED] Kubernetes operator for managing the lifecycle of Apache Flink and Beam applications.
Go
657
star
55

terraform-google-examples

Collection of examples for using Terraform with Google Cloud Platform.
HCL
573
star
56

functions-framework-dart

FaaS (Function as a service) framework for writing portable Dart functions
Dart
535
star
57

cloud-run-button

Let anyone deploy your GitHub repos to Google Cloud Run with a single click
Go
527
star
58

bigquery-oreilly-book

Source code accompanying: BigQuery: The Definitive Guide by Lakshmanan & Tigani to be published by O'Reilly Media
Jupyter Notebook
523
star
59

govanityurls

Use a custom domain in your Go import path
Go
518
star
60

ml-on-gcp

Machine Learning on Google Cloud Platform
Python
484
star
61

practical-ml-vision-book

Jupyter Notebook
482
star
62

getting-started-java

Java
478
star
63

ipython-soccer-predictions

Sample iPython notebook with soccer predictions
Jupyter Notebook
473
star
64

monitoring-dashboard-samples

Google Cloud Monitoring Dashboard Samples
TypeScript
471
star
65

covid-19-open-data

Datasets of daily time-series data related to COVID-19 for over 20,000 distinct locations around the world.
Python
471
star
66

ai-platform-samples

Official Repo for Google Cloud AI Platform. Find samples for Vertex AI, Google Cloud's new unified ML platform at: https://github.com/GoogleCloudPlatform/vertex-ai-samples
Jupyter Notebook
457
star
67

hackathon-toolkit

GCP Hackathon Toolkit
HTML
440
star
68

gradle-appengine-templates

Freemarker based templates that build with the gradle-appengine-plugin
439
star
69

distributed-load-testing-using-kubernetes

Distributed load testing using Kubernetes on Google Container Engine
Smarty
438
star
70

terraform-validator

Terraform Validator is not an officially supported Google product; it is a library for conversion of Terraform plan data to CAI Assets. If you have been using terraform-validator directly in the past, we recommend migrating to `gcloud beta terraform vet`.
Go
437
star
71

cloud-code-vscode

Cloud Code for Visual Studio Code: Issues, Documentation and more
416
star
72

nodejs-docker

The Node.js Docker image used by Google App Engine Flexible.
TypeScript
407
star
73

cloud-ops-sandbox

Cloud Operations Sandbox is an open source collection of tools that helps practitioners to learn O11y and R9y practices from Google and apply them using Cloud Operations suite of tools.
HCL
405
star
74

professional-services-data-validator

Utility to compare data between homogeneous or heterogeneous environments to ensure source and target tables match
Python
403
star
75

k8s-stackdriver

Go
390
star
76

cloud-code-samples

Code templates to make working with Kubernetes feel like editing and debugging local code.
Java
387
star
77

healthcare

Python
374
star
78

require-so-slow

`require`s taking too much time? Profile 'em.
TypeScript
373
star
79

functions-framework-go

FaaS (Function as a service) framework for writing portable Go functions
Go
373
star
80

k8s-multicluster-ingress

kubemci: Command line tool to configure L7 load balancers using multiple kubernetes clusters
Go
372
star
81

compute-image-packages

Packages for Google Compute Engine Linux images.
Python
370
star
82

android-docs-samples

Java
365
star
83

stackdriver-errors-js

Client-side JavaScript exception reporting library for Cloud Error Reporting
JavaScript
358
star
84

applied-ai-engineering-samples

This repository compiles code samples and notebooks demonstrating how to use Generative AI on Google Cloud Vertex AI.
Jupyter Notebook
344
star
85

mlops-with-vertex-ai

An end-to-end example of MLOps on Google Cloud using TensorFlow, TFX, and Vertex AI
Jupyter Notebook
343
star
86

google-cloud-iot-arduino

Google Cloud IOT Example on ESP8266
C++
340
star
87

istio-samples

Istio demos and sample applications for GCP
Shell
331
star
88

ios-docs-samples

iOS samples that demonstrate APIs and services of Google Cloud Platform.
Swift
325
star
89

cloud-code-intellij

Plugin to support the Google Cloud Platform in IntelliJ IDEA - Docs and Issues Repository
319
star
90

security-analytics

Community Security Analytics provides a set of community-driven audit & threat queries for Google Cloud
Python
315
star
91

gke-networking-recipes

Shell
307
star
92

gcping

The source for the CLI and web app at gcping.com
Go
303
star
93

solutions-terraform-cloudbuild-gitops

HCL
301
star
94

spring-cloud-gcp

New home for Spring Cloud GCP development starting with version 2.0.
Java
299
star
95

airflow-operator

Kubernetes custom controller and CRDs to managing Airflow
Go
296
star
96

genai-for-marketing

Showcasing Google Cloud's generative AI for marketing scenarios via application frontend, backend, and detailed, step-by-step guidance for setting up and utilizing generative AI tools, including examples of their use in crafting marketing materials like blog posts and social media content, nl2sql analysis, and campaign personalization.
Jupyter Notebook
296
star
97

elixir-samples

A collection of samples on using Elixir with Google Cloud Platform.
Elixir
291
star
98

gcpdiag

gcpdiag is a command-line diagnostics tool for GCP customers.
Python
288
star
99

kotlin-samples

Kotlin
285
star
100

compute-archlinux-image-builder

A tool to build a Arch Linux Image for GCE
Shell
284
star