A handler processes incoming requests in your Function Compute (FC) function. When a function is invoked, FC routes the request to the handler specified in your function configuration.
To handle HTTP requests through HTTP triggers or custom domain names, see Use an HTTP trigger to invoke a function.
Handler format
Configure the Handler parameter in the Function Compute console using the following format:
[Package name].[Class name]::[Method name]For example, if your package is example, your class is HelloFC, and your method is handleRequest:
example.HelloFC::handleRequestThe package name and class name can be customized, but must match the Handler value in function configuration. See Create an event function.
Handler interfaces
Java handlers must implement an interface from the fc-java-core library:
| Interface | Input/Output | Use when |
|---|---|---|
StreamRequestHandler | InputStream / OutputStream | Processing raw byte streams or data that doesn't map to a POJO |
PojoRequestHandler<I, O> | Custom POJO types | Working with structured JSON data that maps to Java objects |
Maven dependency
Add fc-java-core to your pom.xml:
<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.
Before creating a function, package your code and the fc-java-core dependency into a JAR file. See Compile and deploy code packages.
StreamRequestHandler
StreamRequestHandler reads input from an InputStream and writes output to an OutputStream.
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());
}
}inputStream: Contains the event data passed when the function is invoked.outputStream: Receives the function return data.context: Provides runtime information such as the request ID and temporary AccessKey pair. Type:com.aliyun.fc.runtime.Context. See Context.
PojoRequestHandler
PojoRequestHandler<I, O> uses generic types for input and output. Both types must be Plain Old Java Objects (POJOs) that support JSON serialization.
Handler class
// 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);
}
}Request and response classes
// 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;
}
}Sample input event
{
"firstName": "FC",
"lastName": "aliyun"
}Example: Invoke a function with an HTTP trigger
This example demonstrates a handler that processes HTTP trigger requests and returns HTTP responses.
Prerequisites
Before you begin, ensure that you have:
A function created in a Java runtime with the sample code below. See Create an event function
An HTTP trigger configured for the function. See Configure an HTTP trigger
Sample code
The handler implements PojoRequestHandler with HTTPTriggerEvent and HTTPTriggerResponse as the input and output types. For HTTP trigger request and response formats, see Use an HTTP trigger to invoke a function.
App.java - Entry class
HTTPTriggerEvent.java - Request format
HTTPTriggerResponse.java - Response format
Additional Maven dependencies
Add jackson and lombok alongside fc-java-core:
<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>Invoke the function
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 to manage.
Click the Triggers tab to obtain the public endpoint of the HTTP trigger.
Run the following curl command: Replace the URL with your HTTP trigger's public endpoint. Expected response:
curl -i "https://dev-jav-test-fc-luiqas****.cn-shanghai.fcapp.run" -d 'hello fc3.0'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%
If the Authentication Method of the HTTP trigger is set to No Authentication, use Postman or curl to invoke the function directly.
If the Authentication Method is set to Signature Authentication or JWT Authentication, use the corresponding authentication method. See Authentication.
Common errors
This handler is designed for HTTP trigger invocations. Invoking it through the Test Function button in the console with a plain string input (such as "Hello, FC!") causes a deserialization error:
{
"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)",
"..."
]
}To test this handler, invoke it through the HTTP trigger endpoint or provide a JSON payload that matches the HTTPTriggerEvent structure.
Sample programs
FC provides sample programs that demonstrate different handler types:
java11-blank-stream-event - Stream format event handler
java11-blank-pojo-event - POJO format event handler