Handler
A Java handler responds to received events and runs the corresponding business logic. Review the handler concepts, structural features, and examples in this topic.
If you want to use HTTP triggers or custom domain names to access functions, obtain request struct before you define HTTP responses. For more information, see Use an HTTP trigger to invoke a function.
What is a handler?
FC function handlers are the methods in the function code that handle requests. When your function is invoked, Function Compute runs the handler method that you provide to handle the request.
Use the Function Compute console to configure Handler. For functions written in Java, configure the handler in the following format: [package name].[class name]::[method name]. For example, if your package name is example, your class name is HelloFC, and your method name is handleRequest, configure the handler as example.HelloFC::handleRequest.
Configurations of handlers must conform to the configuration specifications of Function Compute. The configuration specifications vary based on the handler type.
Handler interfaces
When you program in Java, you must implement the interface classes provided by Function Compute. The fc-java-core library defines the following two interfaces for handlers.
-
Receives the input
eventas a stream and returns the execution result. Read the input from the input stream when the function is invoked. After processing is complete, write the function execution result to the output stream to return it. -
Receives the input
eventby using generics and returns the execution result. The input and output types are customizable, but both must be Plain Old Java Object (POJO) types.
StreamRequestHandler
The following example shows the simplest StreamRequestHandler:
package example;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class HelloFC implements StreamRequestHandler {
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
outputStream.write(new String("hello world").getBytes());
}
}
-
Package name and class name
Because Java has the concept of packages, the execution method differs from that of other languages and must include package information. In the code example, the handler is
example.HelloFC::handleRequest, whereexampleis the package name,HelloFCis the class name, andhandleRequestis the class method.NoteThe package name and class name can be arbitrary, but they must match the Handler field in the function configuration. To configure Handler, see Create an event-triggered function.
-
Implemented interface
Your code must implement the interface predefined by Function Compute. The preceding code example implements
StreamRequestHandler, where the inputStream parameter is the data passed in when the function is invoked. The outputStream parameter returns the execution result of the function. -
Context parameter
The Context parameter contains runtime information about the function, such as the RequestId and a temporary AccessKey. Its type is
com.aliyun.fc.runtime.Context. For details, see Context. -
Return value
A function that implements the
StreamRequestHandlerinterface returns the execution result through theoutputStreamparameter. -
Interface library
The dependency on the
com.aliyun.fc.runtimepackage used in this example can be referenced in the followingpom.xmlfile:<dependency> <groupId>com.aliyun.fc.runtime</groupId> <artifactId>fc-java-core</artifactId> <version>1.4.1</version> </dependency>Check the Maven repository for the latest version number of
fc-java-core.
Before you create a function, package your code and its fc-java-core dependency into a JAR file. For instructions, see Compile and deploy a code package.
PojoRequestHandler
The following example shows the simplest PojoRequestHandler. The SimpleRequest object must support JSON serialization. A POJO meets this requirement.
// HelloFC.java
package example;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;
public class HelloFC implements PojoRequestHandler<SimpleRequest, SimpleResponse> {
@Override
public SimpleResponse handleRequest(SimpleRequest request, Context context) {
String message = "Hello, " + request.getFirstName() + " " + request.getLastName();
return new SimpleResponse(message);
}
} // SimpleRequest.java
package example;
public class SimpleRequest {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public SimpleRequest() {}
public SimpleRequest(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
} // SimpleResponse.java
package example;
public class SimpleResponse {
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SimpleResponse() {}
public SimpleResponse(String message) {
this.message = message;
}
}
The following is an example of the event parameter that is passed in:
{
"firstName": "FC",
"lastName": "aliyun"
}
Example: Use an HTTP trigger to invoke a function
Sample code
In the preceding sample code, HTTPTriggerEvent.java declares the request format of the HTTP trigger, and HTTPTriggerResponse.java declares the response format of the HTTP trigger. For details about the HTTP trigger request struct and response struct formats, see Use an HTTP trigger to invoke a function.
App.java defines the function entry point class.
In addition to the fc-java-core library, this sample program also requires two additional libraries, jackson and lombok. Add these dependencies to the Maven configuration file pom.xml.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
Prerequisites
You have used the preceding example to create a function that uses the Java runtime, and created an HTTP trigger. For instructions, see Create an event-triggered function and Configure an HTTP trigger.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
-
On the function details page, click the Triggers tab. On the Triggers page, get the public network access address of the HTTP trigger.
-
Invoke the function with the following curl command:
curl -i "https://dev-jav-test-fc-luiqas****.cn-shanghai.fcapp.run" -d 'hello fc3.0'In the preceding command,
https://dev-jav-test-fc-luiqas****.cn-shanghai.fcapp.runis the public network access address of the HTTP trigger that you obtained.The following response is returned:
HTTP/1.1 200 OK Content-Disposition: attachment Content-Length: 11 Content-Type: application/json X-Fc-Request-Id: 1-652503f2-afbfd2b1dc4dd0fcb0230959 Date: Tue, 10 Oct 2023 07:57:38 GMT hello fc3.0%Important-
If the Authentication Method of the HTTP trigger is No Authentication, you can use Postman or the Curl tool to invoke the function directly. For instructions, see Procedure in this topic.
-
If the Authentication Method of the HTTP trigger is Signature Authentication, JWT authentication, or Bearer authentication, use the signature method, JWT authentication, or Bearer authentication to invoke the function. For instructions, see Authentication and authorization.
-
Error analysis
This sample code supports invocation by using an HTTP trigger or a custom domain name. If you invoke the function by using an API but the configured test parameters do not comply with the HTTP trigger request format specification, an error is reported.
For example, when you invoke the function in the console, set the request parameter to "Hello, FC!", and click Test Function. The following response is returned:
{
"errorType": "com.fasterxml.jackson.databind.exc.MismatchedInputException",
"errorMessage": "Cannot construct instance of `example.HTTPTriggerEvent` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('Hello, FC!')\n at [Source: (byte[])\"\"Hello, FC!\"\"; line: 1, column: 1]",
"stackTrace": [
"com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)",
"com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1588)",
"com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1213)",
"com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromString(StdDeserializer.java:311)",
"com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1495)",
"com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:207)",
"com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:197)",
"com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:322)",
"com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4593)",
"com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3643)"
]
}
Sample programs
Function Compute's official library contains sample applications that use various handler types and interfaces. Each sample application includes a method for easy compilation and deployment. For example:
-
java11-blank-stream-event: An event callback handler that uses the Stream format.
-
java11-blank-pojo-event: An event callback handler that uses the POJO format.