OpenFaaS实战之八:自制模板(maven+jdk8),美团java面试算法题

本文介绍了如何使用OpenFaaS创建一个基于maven和jdk8的模板,用于解决美团面试中的算法题。通过编写Dockerfile,设置镜像构建过程,包括配置maven的settings.xml,使用openfaas/of-watchdog,并构建最终的Docker镜像。同时,提供了Handler.java的示例代码,展示了如何处理请求并返回响应。最后,验证了模板的可用性,通过faas-cli创建和部署函数,完成模板的实战应用。
摘要由CSDN通过智能技术生成
  1. openfaas的model和entrypoint这两个jar是整个服务可运行的基础;

  2. 有些常用的jar依赖也被加入了,您可以酌情自行增删;

  3. 插件maven-compiler-plugin用来指定编译时的JDK版本;

  4. 插件maven-dependency-plugin和maven-assembly-plugin用来将整个java代码和依赖库打包到一个jar文件中,这样制作Docker镜像会方便很多;

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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值