Sip a cup of Java 11 in your Cloud Features
Posted by Guillaume Laforge, Developer Advocate for Google Cloud
With the beta of the brand new Java 11 runtime for Google Cloud Features, Java builders can now write their features utilizing the Java programming language (a language usually utilized in enterprises) along with Node.js, Go, or Python. Cloud Features will let you run bits of code regionally or within the cloud, with out provisioning or managing servers: Deploy your code, and let the platform deal with scaling up and down for you. Simply focus in your code: deal with incoming HTTP requests or reply to some cloud occasions, like messages coming from Cloud Pub/Sub or new information uploaded in Cloud Storage buckets.
On this article, let’s concentrate on what features appear to be, how one can write moveable features, how one can run and debug them regionally or deploy them within the cloud or on-premises, because of the Features Framework, an open supply library that runs your features. However additionally, you will find out about third-party frameworks that you just is likely to be conversant in, that additionally allow you to create features utilizing frequent programming paradigms.
There are two kinds of features: HTTP features, and background features. HTTP features reply to incoming HTTP requests, whereas background features react to cloud-related occasions.
The Java Features Framework supplies an API that you need to use to creator your features, in addition to an invoker which could be referred to as to run your features regionally in your machine, or anyplace with a Java 11 atmosphere.
To get began with this API, you’ll need so as to add a dependency in your construct information. If you happen to use Maven, add the next dependency tag in pom.xml:
In case you are utilizing Gradle, add this dependency declaration in construct.gradle:
Responding to HTTP requests
A Java perform that receives an incoming HTTP request implements the HttpFunction interface:
public class Instance implements HttpFunction
public void service(HttpRequest request, HttpResponse response)
var author = response.getWriter();
The service() methodology supplies an HttpRequest and an HttpResponse object. From the request, you may get details about the HTTP headers, the payload physique, or the request parameters. It’s additionally doable to deal with multipart requests. With the response, you’ll be able to set a standing code or headers, outline a physique payload and a content-type.
Responding to cloud occasions
Background features reply to occasions coming from the cloud, like new Pub/Sub messages, Cloud Storage file updates, or new or up to date knowledge in Cloud Firestore. There are literally two methods to implement such features, both by coping with the JSON payloads representing these occasions, or by profiting from object marshalling because of the Gson library, which takes care of the parsing transparently for the developer.
With a RawBackgroundFunction, the duty is on you to deal with the incoming cloud occasion JSON-encoded payload. You obtain a JSON string, so you might be free to parse it nevertheless you want, along with your JSON parser of your selection:
public class RawFunction implements RawBackgroundFunction
public void settle for(String json, Context context)
However you even have the choice to write down a BackgroundFunction which makes use of Gson for unmarshalling a JSON illustration right into a Java class (a POJO, Plain-Previous-Java-Object) representing that payload. To that finish, it’s a must to present the POJO as a generic argument:
public class PubSubFunction implements BackgroundFunction
public class PubSubMsg
The Context parameter comprises varied metadata fields like timestamps, the kind of occasions, and different attributes.
Which sort of background perform do you have to use? It relies on the management that you must have on the incoming payload, or if the Gson unmarshalling doesn’t totally suit your wants. However having the unmarshalling coated by the framework positively streamlines the writing of your perform.
Coding is all the time nice, however seeing your code really operating is much more rewarding. The Features Framework comes with the API we used above, but in addition with an invoker device that you need to use to run features regionally. For enhancing developer productiveness, having a direct and native suggestions loop by yourself pc makes it far more comfy than deploying within the cloud for every change you make to your code.
If you happen to’re constructing your features with Maven, you’ll be able to set up the Operate Maven plugin in your pom.xml:
On the command-line, you’ll be able to then run:
$ mvn perform:run
You possibly can cross further parameters like –target to outline a unique perform to run (in case your challenge comprises a number of features), –port to specify the port to take heed to, or –classpath to explicitly set the classpath wanted by the perform to run. These are the parameters of the underlying Invoker class. Nevertheless, to set these parameters by way of the Maven plugin, you’ll should cross properties with -Drun.functionTarget=com.instance.Instance and -Drun.port.
With Gradle, there isn’t any devoted plugin, however it’s simple to configure construct.gradle to allow you to run features.
First, outline a devoted configuration for the invoker:
Within the dependencies, add the Invoker library:
After which, create a brand new activity to run the Invoker:
predominant = ‘com.google.cloud.features.invoker.runner.Invoker’
challenge.findProperty(‘runFunction.port’) ?: 8080
By default, the above launches the perform com.instance.Instance on port 8080, however you’ll be able to override these on the command-line, when operating gradle or the gradle wrapper:
$ gradle runFunction -PrunFunction.goal=com.instance.HelloWorld
Working elsewhere, making your features moveable
What’s attention-grabbing in regards to the Features Framework is that you’re not tied to the Cloud Features platform for deploying your features. So long as, in your goal atmosphere, you’ll be able to run your features with the Invoker class, you’ll be able to run your features on Cloud Run, on Google Kubernetes Engine, on Knative environments, on different clouds when you’ll be able to run Java, or extra typically on any servers on-premises. It makes your features extremely moveable between environments. However let’s have a better take a look at deployment now.
You possibly can deploy features with the Maven plugin as nicely, with varied parameters to tweak for outlining areas, reminiscence measurement, and so on. However right here, we’ll concentrate on utilizing the cloud SDK, with its gcloud command-line, to deploy our features.
For instance, to deploy an HTTP perform, you’ll kind:
$ gcloud features deploy exampleFn
For a background perform that might be notified of latest messages on a Pub/Sub subject, you’ll launch:
$ gcloud features deploy exampleFn
Observe that deployments are available in two flavors as nicely, though the above instructions are the identical: features are deployed from supply with a pom.xml and in-built Google Cloud, however when utilizing a construct device apart from Maven, you may also use the identical command to deploy a pre-compiled JAR that comprises your perform implementation. After all, you’ll should create that JAR first.
Up to now, we checked out Java and the plain Features Framework, however you’ll be able to positively use various JVM languages akin to Apache Groovy, Kotlin, or Scala, and third-party frameworks that combine with Cloud Features like Micronaut and Spring Boot!
Fairly Groovy features
With out overlaying all these combos, let’s take a look at two examples. What would an HTTP perform appear to be in Groovy?
Step one might be so as to add Apache Groovy as a dependency in your pom.xml:
Additionally, you will want the GMaven compiler plugin to compile the Groovy code:
When writing the perform code, simply use Groovy as an alternative of Java:
class HelloWorldFunction implements HttpFunction
The identical explanations concerning operating your perform regionally or deploying it nonetheless applies: the Java platform is fairly open to various languages too! And the Cloud Features builder will fortunately construct your Groovy code within the cloud, since Maven permits you to compile this code because of the Groovy library.
Third-party frameworks additionally provide a devoted Cloud Features integration. Let’s take a look at Micronaut.
Micronaut is a “fashionable, JVM-based, full-stack framework for constructing modular, simply testable microservice and serverless functions”, as defined on its web site. It helps the notion of serverless features, internet apps and microservices, and has a devoted integration for Google Cloud Features.
Along with being a really environment friendly framework with tremendous quick startup instances (which is vital, to keep away from lengthy chilly begins on serverless providers), what’s attention-grabbing about utilizing Micronaut is that you need to use Micronaut’s personal programming mannequin, together with Dependency Injection, annotation-driven bean declaration, and so on.
For HTTP features, you need to use the framework’s personal @Controller / @Get annotations, as an alternative of the Features Framework’s personal interfaces. So for instance, a Micronaut HTTP perform would appear to be:
public class HelloController
@Get(uri=”/”, produces=”textual content/plain”)
public String index()
That is the usual means in Micronaut to outline a Internet microservice, however it transparently builds upon the Features Framework to run this service as a Cloud Operate. Moreover, this programming mannequin provided by Micronaut is moveable throughout different environments, since Micronaut runs in many alternative contexts.
Final however not least, if you’re utilizing the Micronaut Launch challenge (hosted on Cloud Run) which lets you scaffold new initiatives simply (from the command-line or from a pleasant UI), you’ll be able to go for including the google-cloud-function help module, and even select your favourite language, construct device, or testing framework:
Remember to try the documentation for the Micronaut Cloud Features help, and Spring Cloud Operate help.
Now it’s your flip to attempt Cloud Features for Java 11 in the present day, along with your favourite JVM language or third-party frameworks. Learn the getting began information, and do that at no cost with Google Cloud Platform free trial. Discover Cloud Features’ options and use circumstances, check out the quickstarts, maybe even contribute to the open supply Features Framework. And we’re trying ahead to seeing what features you’re going to construct on this platform!