In my last post we took a look at how to create serverless functions which interact with an Autonomous Transaction Processing (ATP) instance. We invoked those functions using the Fn CLI, which was handy for testing, but obviously not so helpful when it comes to integrating these functions into our microservice applications. There are in fact several ways to invoke Oracle Functions, but in this post we'll focus on calling them via the OCI Java SDK.
To get started, we'll need to include the OCI Java SDK in our project. I'm using Gradle this time, so my dependency looks like so (notice line 6):
To invoke our function, we'll need to know two things: the function 'invokeEndpoint' and the function OCID. There's an easy way to grab both of these using the Fn CLI by calling '
Which will result in output similar to this:
Using the example above, The endpoint variable would be: `https://xicciwch3fq.us-phoenix-1.functions.oci.oraclecloud.com` and the function OCID would be the value within the "id" attribute (
ocid1.fnfunc....). Now that we have these two values, we can invoke our function with the OCI SDK. The examples below will show invoking a few of the Node.JS serverless functions that persist JSON data as shown in my last post.
First, let's set some variables for our endpoint and function ID, create an
AuthenticationDetailsProvider and generate a JSON payload to be sent to the insert function. These examples will use Groovy, but this should look extremely familiar to Java and could very easily be ported to Java with minimal effort:
We have two options for invoking the functions via the SDK: synchronous or asynchronous. First, let's look at invoking them synchronously. We'll do that by creating a
FunctionsInvokeClient which accepts our
AutoCloseable, so we'll use Groovy's
withCloseable to make sure things are cleaned up when we're done. The
withCloseable closure will receive the client as its only argument and we can use that from within the closure.
To break down the code below, we'll do the following steps:
Which results in the following output:
To invoke the functions asynchronously is nearly identical, but we now use the
FunctionsInvokeAsyncClient and the
invokeFunction methods now receive an instance of
AsyncHandler to handle the response.
The async invocation produces the following output. Take note of the order and timestamps on the logging output:
Using the SDK and the Fn CLI is not the only way to invoke Oracle Functions from your application. You can also call the invokeEndpoint directly, but you'll need to sign the HTTP request as you would any other REST call to the OCI API.