应用健康检查

一:背景

   我们的应用是都是走自动化脚本发布的,当发布完成后,通常的做法可能是直接看发布日志是否有报错,但这需要人工去操作,所以我们写了一个健康检查的页面,在发布完成后用脚本去访问这个健康页面,看是否能正常访问,从而确定应用是否正常启动。

二:实现

  •   写一个servlet去作为健康检查的页面,如果能正常访问,说明应用启动成功
  •   写一个filter做安全检查,禁止访问其他资源

三:代码

       servlet
public class AppHealthCheckServlet extends HttpServlet {


    /**
     * 
     */
    private static final long serialVersionUID = -1828845486756970600L;
    /** 默认健康检查页面 */
    private static final String DEFAULT_LOCATION = "/web/templates/screen/ok.html";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        resp.setCharacterEncoding("UTF-8");
        //2.获取健康检查页面的location
        //        String location = req.getServletContext().getInitParameter("health");
        String location = req.getSession().getServletContext().getInitParameter("health");
        location = StringUtils.isBlank(location) ? DEFAULT_LOCATION : location;
        //3.跳转页面
        //        resp.sendRedirect(location);
        req.getRequestDispatcher(location).forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    filter
public class AccessControlFilter implements Filter {

    /** 无权限默认访问的路径 */
    private static final String ERRORLOCATION = "/web/templates/screen/access.html";

    /** 有权限访问的路径 */
    private static final String ACCESS_URI    = "/ok";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String URI = req.getRequestURI();
        if (ACCESS_URI.equals(URI)) {
            chain.doFilter(request, response);
        } else {
            String selfLocation = req.getSession().getServletContext().getInitParameter("access");
            selfLocation = StringUtils.isBlank(selfLocation) ? ERRORLOCATION : selfLocation;
            request.getRequestDispatcher(selfLocation).forward(request, response);
        }
    }

    @Override
    public void destroy() {

    }

    web.xml配置

		health
		com.xxxx.core.bridge.servlet.AppHealthCheckServlet
		
			health
			/web/templates/screen/ok.html
		
	
	
		health
		/ok
	
	
	
		access
		 com.xxxx.core.bridge.filter.AccessControlFilter
		
			access
			/web/templates/screen/access.html
		
	
	
		access
		/*
	



你可能感兴趣的:(架构设计)