Spring MVC uses stub layer

Keywords: JSON Redis Java Tomcat

Premise of use:

stub dummy data is used when the interface does not exist (i.e. message 404)

Entrance:

In BusinessExceptionHandlerAdvice

NoHandlerFoundException

Exception capture method

Flow chart

 

Where is the configuration file read?

In oa/web/controller/handler/EnvironmentInit.java,

EnvironmentInit implements ApplicationListener,

So after the tomcat application starts successfully, it will execute,

Read the configuration file in the onApplicationEvent method,

Profile path:

"/config/stubMap.json"

EnvironmentInit source code:

package oa.web.controller.handler;

import com.file.hw.props.GenericReadPropsUtil;
import com.io.hw.json.HWJacksonUtils;
import com.string.widget.util.RegexUtil;
import com.string.widget.util.ValueWidget;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.util.Map;

/**
 * Created by Huang Wei on March / 22 / 18. < br >
 * The core class to read the configuration file is the only entry to get the properties parameter < br >
 * Execution order < br >
 * Annotate the setter method of Resource < br >
 * The setServletContext method to implement interface ServletContextAware < br >
 * onApplicationEvent Methods <br / >
 * config/stubMap.json Format of: < br / >
 * <code>
 *     {
 *   "/a/b/c": "a_b_c",
 *   "/house/recommended/listfilter/json": "recommendedList",
 *   "ccc": "ddd",
 *   "ccc": "ddd",
 *   "test": "test"
 * }
 *     </code> <br />
 *     key Is the interface path, it is recommended to start with a slash, < br / >
 *     value It's the key of redis < br / >
 *     How to set the stub response content?: < br / >
 *     Through the interface: http://127.0.0.1:8080/redis/setCache, pass the parameters: ID, key, value < br / >
 *     Configuration file path: < br / >
 *     /src/main/resources/config/stubMap.json
 */
@Configuration
public class EnvironmentInit implements ApplicationListener<ContextRefreshedEvent>, ServletContextAware {
    private ServletContext servletContext;
    private Map<String, String> stubPathMap;

    //    @Resource
//    private RequestSafeThreadParamDto requestSafeThreadParamDto;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (!ValueWidget.isNullOrEmpty(getStubPathMap())) {
            return;
        }
        ClassLoader classLoader = this.servletContext.getClassLoader();
        String resourcePath = "/config/stubMap.json";
        String json = GenericReadPropsUtil.getConfigTxt(classLoader, resourcePath);
        if (null != json) {
            json = RegexUtil.sedDeleteComment(json);//Delete comment on first line
            setStubPathMap(HWJacksonUtils.deSerializeMap(json, String.class));
        }
    }


    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public Map<String, String> getStubPathMap() {
        return stubPathMap;
    }

    public void setStubPathMap(Map<String, String> stubPathMap) {
        this.stubPathMap = stubPathMap;
    }
}

 

Where to store stub fake data

Stored in redis,

So how to get redis key through interface path?

Through the following methods:

 String redisKey = servletActionMap.get(path);
        if (null == redisKey && path.startsWith("/")) {//For example, if you can't find "/ agent/list/json", go to "agent/list/json"
            redisKey = servletActionMap.get(path.substring(1, path.length()));
        }
        if (null == redisKey) {//For example, if "agent/list/json" cannot be found, then "agent list JSON" can be found
            redisKey = path.replace("/", "_");
            if (redisKey.startsWith("_")) {
                redisKey.substring(1, redisKey.length());
            }
        }

Note: the path parameter in the above code is

request.getServletPath()

For example, the interface path is "/ agent/list/json",

Then take "/ agent/list/json" as the key of the map, and search from the map,

If it cannot be found, set the

"agent_list_json"

As a redis key

Where can I get the map of the map?

Get it from two places:

1. Local profile (low priority):

"/config/stubMap.json"

The content is as follows (example):

/*** Will be called by oa/web/controller/handler/EnvironmentInit.java**/
{
  "/a/b/c": "a_b_c",
  "house/recommended/listfilter/json": "recommendedList",
  "ccc": "ddd",
  "ccc": "ddd",
  "test": "test"
}

2. It is obtained from redis with high priority, so the local file configuration will be overwritten

Be careful:

1. map in redis has higher priority than "/ config/stubMap.json";

2. If it is judged that the stub data obtained from redis is empty, the normal process will continue

Reference: https://my.oschina.net/huangweiindex/blog/1632499

Posted by david4u on Fri, 03 Apr 2020 05:10:15 -0700