-
openfaas的model和entrypoint这两个jar是整个服务可运行的基础;
-
有些常用的jar依赖也被加入了,您可以酌情自行增删;
-
插件maven-compiler-plugin用来指定编译时的JDK版本;
-
插件maven-dependency-plugin和maven-assembly-plugin用来将整个java代码和依赖库打包到一个jar文件中,这样制作Docker镜像会方便很多;
- 新建一个java类:com.openfaas.function.Handler,源码和《OpenFaaS实战之三:Java函数》中的Handler.java一模一样,如下:
package com.openfaas.function;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openfaas.model.IRequest;
import com.openfaas.model.IResponse;
import com.openfaas.model.Response;
import org.apache.commons.lang3.StringUtils;
import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class Handler extends com.openfaas.model.AbstractHandler {
private static final String PARAM_USER_NAME = “name”;
private static final String RESPONSE_TEMPLETE = “Hello %s, response from [%s], PID [%s], %s”;
private ObjectMapper mapper = new ObjectMapper();
/**
-
获取本机IP地址
-
@return
*/
public static String getIpAddress() {
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println(“IP地址获取失败” + e.toString());
}
return “”;
}
/**
-
返回当前进程ID
-
@return
*/
private static String getPID() {
return ManagementFactory
.getRuntimeMXBean()
.getName()
.split("@")[0];
}
private String getUserName(IRequest req) {
// 如果从请求body中取不到userName,就用
String userName = null;
try {
Map<String, Object>