Welcome to my GitHub

Github.com/zq2599/blog…

Content: all original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;

Links to OpenFaaS Field series articles

  1. The deployment of
  2. Introduction to the function
  3. Java functions
  4. Template operation (Template)
  5. Big watchdog
  6. Of -watchdog(For performance)
  7. Java11 template parsing
  8. Maven +jdk8
  9. Maven +maven+jdk8

This paper gives an overview of

  1. This article is the third part of OpenFaaS Actual Combat series. After the actual combat, we have mastered the essentials of function development and deployment. As a Java programmer, of course, we are eager to write OpenFaaS functions in Java, so we have this article.
  2. This article develops a Java function that parses the JSON string in the request body, plus the JVM process ID, IP address, and current time into a string, and returns it wrapped in JSON.
  3. We usually use a variety of binary libraries to write Java code. Jackson’s library is introduced here as a reference for OpenFaaS to add dependencies.

Download the source code

  • The source code for this article can be downloaded on GitHub, with the address and link information shown in the following table (github.com/zq2599/blog…
The name of the link note
Project home page Github.com/zq2599/blog… The project’s home page on GitHub
Git repository address (HTTPS) Github.com/zq2599/blog… The project source warehouse address, HTTPS protocol
Git repository address (SSH) [email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  • This git project has multiple folders. The application in this chapter is in the OpenFaas folder, as shown in the red box below:

  • There are several subfolders in OpenFaAS. The source of this piece is in CurrentTime, as shown in the red box below:

Create a function

  1. Execute the following command to create a function named faas-CurrentTime with the mirror prefix bolingCavalry and language type Java11:
faas-cli new faas-currenttime --lang java11 -p bolingcavalry
Copy the code
  1. The console responds as follows:
[root@node1 20]# faas-cli new faas-currenttime --lang java11 -p bolingcavalry 2020/11/20 15:47:50 No templates found in current directory. 2020/11/20 15:47:50 Attempting to expand templates from https://github.com/openfaas/templates.git 2020/11/20 15:47:56 Fetched 12 template(s) : [csharp dockerfile go java11 java11-vert-x node node12 php7 python python3 python3-debian ruby] from https://github.com/openfaas/templates.git Folder: faas-currenttime created. ___ _____ ____ / _ \ _ __ ___ _ __ | ___|_ _ __ _/ ___| | | | | '_ \ / _ \ '_ \| |_ / _` |/ _`  \___ \ | |_| | |_) | __/ | | | _| (_| | (_| |___) | \___/| .__/ \___|_| |_|_| \__,_|\__,_|____/ |_| Function created in  folder: faas-currenttime Stack file written: faas-currenttime.yml Notes: You have created a function using the java11 template which uses an LTS version of the OpenJDK.Copy the code
  1. The file faas-currentTime. yml and folder faas-currentTime have been added to the current directory
  2. The folder faas-currentTime contains the following contents:
├─ ├─ class-Bass ├─ Class-bass ├─ class-bass ├─ class-bass ├─ class-Bass ├─ class-Bass ├── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ─ Manule.java ├ ─ 08.08.08.java ├ ─ manule.java ├ ─ manule.javaCopy the code
  1. Open the build.gradle file and add the Jackson and Common library dependencies as shown in the red box below:

  1. Enter the folder faas currenttime/SRC/main/Java/com/openfaas/function /, visible has created the default business function class Handler. Java, open and see openfaas for what the default code, as shown below:
package com.openfaas.function;

import com.openfaas.model.IHandler;
import com.openfaas.model.IResponse;
import com.openfaas.model.IRequest;
import com.openfaas.model.Response;

public class Handler extends com.openfaas.model.AbstractHandler {

    public IResponse Handle(IRequest req) {
        Response res = new Response();
            res.setBody("Hello, world!");

            returnres; }}Copy the code
  1. The Handler. Java function retrieves the request parameters, concatenates the current JVM process ID, IP address, and current time into a string. Deserializing the request parameters into a Map instance, and serializing the Map into a JSON string returns:
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();


    /** * Obtain the local IP address *@return* /
    public static String getIpAddress(a) {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if(netInterface.isLoopback() || netInterface.isVirtual() || ! netInterface.isUp()) {continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if(ip ! =null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to obtain IP address" + e.toString());
        }
        return "";
    }

    /** * returns the current process ID *@return* /
    private static String getPID(a) {
        return ManagementFactory
                .getRuntimeMXBean()
                .getName()
                .split("@") [0];
    }


    private String getUserName(IRequest req) {
        // If you can't get userName from the request body, use it
        String userName = null;

        try {
            Map<String, Object> mapFromStr = mapper.readValue(req.getBody(),
                    new TypeReference<Map<String, Object>>() {});

            if(null!=mapFromStr && mapFromStr.containsKey(PARAM_USER_NAME)) {
                userName = String.valueOf(mapFromStr.get(PARAM_USER_NAME));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // If you can't get userName from the request body, give a default value
        if(StringUtils.isBlank(userName)) {
            userName = "anonymous";
        }

        return userName;
    }

    public IResponse Handle(IRequest req) {

        String userName = getUserName(req);

        System.out.println("1 -" + userName);

        // Return information with the IP address, process number, and time of the current JVM machine
        String message = String.format(RESPONSE_TEMPLETE,
                userName,
                getIpAddress(),
                getPID(),
                new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" ).format(new Date()));

        System.out.println(2. -- -- -- "" + message);

        // The response content is also in JSON format, so it is first stored in map and then serialized
        Map<String, Object> rlt = new HashMap<>();
        rlt.put("success".true);
        rlt.put("message", message);

        String rltStr = null;

        try {
            rltStr = mapper.writeValueAsString(rlt);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Response res = new Response();
        res.setContentType("application/json; charset=utf-8");
        res.setBody(rltStr);

	    returnres; }}Copy the code
  • Now that the coding is complete, the next step is mirroring and deployment;

The deployment of

  1. Run the following command in the directory where faas-currentTime. yml is located to start creating an image:
faas-cli build -f ./faas-currenttime.yml
Copy the code
  1. When the image is successfully created, information similar to the following is displayed on the console:
Step 27/30 : ENV fprocess="java -XX:+UseContainerSupport com.openfaas.entrypoint.App"
---> Running in 0f50636cc747
Removing intermediate container 0f50636cc747
---> 54a5c9a193c8
Step 28/30 : EXPOSE 8080
---> Running in 3252f165af15
Removing intermediate container 3252f165af15
---> c05afc826ec5
Step 29/30 : HEALTHCHECK --interval=5s CMD [ -e /tmp/.lock ] || exit 1
---> Running in 4106410be0a2
Removing intermediate container 4106410be0a2
---> 6d95b73b5f33
Step 30/30 : CMD ["fwatchdog"]
---> Running in 1606dbcd7003
Removing intermediate container 1606dbcd7003
---> 99a519ab82fdSuccessfully built 99a519ab82fd Successfully tagged bolingcavalry/faas-currenttime:latest Image: Bolingcavalry/FaAS-CurrentTime :latest built. [0] < Building faas-currentTime done in 34.94s. [0] Worker done. Total The build time: 34.94 sCopy the code
  1. Push the image to the mirror warehouse so that Kubernetes can download the image. I used hub.docker.com here, because my ID is BolingCavalry, I can push the image successfully by executing the following command:
docker push bolingcavalry/faas-currenttime:latest
Copy the code
  1. Execute the following command to deploy the function to OpenFaaS:
faas-cli deploy -f faas-currenttime.yml
Copy the code
  1. The console responds with the following, indicating that deployment has started and an endpoint is given:
[root@node1 20]# faas-cli deploy -f faas-currenttime.yml
Deploying: faas-currenttime.
WARNING! Communication is not secure, please consider using HTTPS. Letsencrypt.org offers free SSL/TLS certificates.

Deployed. 202 Accepted.
URL: http://192.168.133.187:31112/function/faas-currenttime.openfaas-fn
Copy the code
  1. When you open the Web side, you can see the newly added function on the page. The verification operation is as shown in the figure below. It can be seen that the JSON content of the input parameter can be parsed normally:

  1. You can also use the curl command on the console:
[root@node1 20]# curl \
> -H "Content-Type: application/json" \
> -X POST \
> --data '{"name":"Jerry}' \
> http://192.168.133.187:31112/function/faas-currenttime
{"success":true,"message":"Hello anonymous, response from [10.233.90.79], PID [11], 2020-11-20 02:14:46"}
Copy the code
  1. Run the faas-cli deploy -f faas-currentTime. yml command to start the deployment. The console accepts the deployment request and provides the endpoint of the function:
[root@node1 20]# faas-cli deploy -f faas-currenttime.yml
Deploying: faas-currenttime.
WARNING! Communication is not secure, please consider using HTTPS. Letsencrypt.org offers free SSL/TLS certificates.

Deployed. 202 Accepted.
URL: http://192.168.133.187:31112/function/faas-currenttime.openfaas-fn
Copy the code

Clean up the

  • To delete the function, run the following command: faas-currentTime. yml
faas-cli remove -f faas-currenttime.yml
Copy the code
  • At this point, the development, deployment, and validation of the most basic Java functions have been completed. If you are also planning to develop OpenFaaS functions in Java, I hope this article will give you some references.

You are not alone, Xinchen original accompany all the way

  1. Java series
  2. Spring series
  3. The Docker series
  4. Kubernetes series
  5. Database + middleware series
  6. The conversation series

Welcome to pay attention to the public number: programmer Xin Chen

Wechat search “programmer Xin Chen”, I am Xin Chen, looking forward to enjoying the Java world with you…

Github.com/zq2599/blog…