在函数计算中使用Java编程时,需要定义一个函数作为入口函数。为函数设置HTTP触发器后,可以方便处理发来的HTTP请求。
HTTP函数接口
函数计算提供基于Servlet协议的HTTP入口,形式如下所示。
public interface HttpRequestHandler {
/**
* The entrance function of fc http trigger
* @param request The servlet request
* @param response The servlet response
* @param context The fc context
* @throws IOException If IO exception happened
* @throws ServletException If servlet exception happened
*/
public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) throws IOException, ServletException;
}
使用HTTP触发器需要将fc-java-core
库版本升级到1.3.0及以上。
HTTP触发器的简单示例
package com.aliyun.fc.example;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.HttpRequestHandler;
public class Hello implements HttpRequestHandler {
public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context)
throws IOException, ServletException {
String requestPath = (String) request.getAttribute("FC_REQUEST_PATH");
String requestURI = (String) request.getAttribute("FC_REQUEST_URI");
String requestClientIP = (String) request.getAttribute("FC_REQUEST_CLIENT_IP");
response.setStatus(200);
response.setHeader("header1", "value1");
response.setHeader("header2", "value2");
String body = String.format("Path: %s\n Uri: %s\n IP: %s\n", requestPath, requestURI, requestClientIP);
OutputStream out = response.getOutputStream();
out.write((body).getBytes());
out.flush();
out.close();
}
}
- HttpServletRequest
函数计算HTTP触发器的接口使用标准的Servlet协议。您的请求会封装成HttpServletRequest对象,请求参数、请求头等均可通过此对象获取。除此之外,函数计算在HttpServletRequest中预封装了一些属性,您可以通过getAttribute方法来获取,具体包括以下内容:
-
FC_REQUEST_PATH:获取请求的路径。
-
FC_REQUEST_URI:获取请求的URI。
-
FC_REQUEST_CLIENT_IP:获取请求的Client IP地址。
-
- HttpServletResponse
您可以通过标准的HttpServletResponse协议对象来返回响应头和响应体。
- context参数
context参数中包含一些函数的运行时信息(例如Request ID、临时AccessKey等),其类型是
com.aliyun.fc.runtime.Context
。
HTTP触发器支持传统Web应用
基于Servlet协议的传统Web应用能很方便地迁移到函数计算平台,目前支持的主流框架包括Spring、SpringBoot、Struts2等。以下示例演示如何通过函数计算提供的fc-java-common
库加载Web应用。
更多信息
HTTP触发器的使用,请参见HTTP触发器概述。