在管理端口上的Spring Boot中公开Togglz管理控制台

时间:2016-11-28 18:42:08

标签: spring-boot togglz

默认情况下,Togglz管理控制台在应用程序端口上运行(由server.port属性配置)。我想在management.port上公开它。我的问题:这可能吗?

1 个答案:

答案 0 :(得分:3)

如果您使用Togglz> = 2.4.0,则可以直接使用此功能。

对于旧版本,解决方案如下:

我设法通过用management.port包装来在MvcEndpoint上公开原始servlet。 最简单的方法是使用Spring Cloud模块为您完成所有工作(例如在HystrixStreamEndpoint中):

public class HystrixStreamEndpoint extends ServletWrappingEndpoint {

    public HystrixStreamEndpoint() {
        super(HystrixMetricsStreamServlet.class, "hystrixStream", "/hystrix.stream",
                true, true);
    }

}

TogglzConsoleServlet的情况下,遗憾的是,由于它从请求URI中提取前缀的方式,还有一个与路径有关的问题,因此整个解决方案看起来有点难看:

@Component
class TogglzConsoleEndpoint implements MvcEndpoint {

    private static final String ADMIN_CONSOLE_URL = "/togglz-console";
    private final TogglzConsoleServlet togglzConsoleServlet;

    @Autowired
    TogglzConsoleEndpoint(final ServletContext servletContext) throws ServletException {
        this.togglzConsoleServlet = new TogglzConsoleServlet();
        togglzConsoleServlet.init(new DelegatingServletConfig(servletContext));
    }

    @Override
    public String getPath() {
        return ADMIN_CONSOLE_URL;
    }

    @Override
    public boolean isSensitive() {
        return true;
    }

    @Override
    public Class<? extends Endpoint> getEndpointType() {
        return null;
    }

    @RequestMapping("**")
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) {
            @Override
            public String getServletPath() {
                return ADMIN_CONSOLE_URL;
            }
        };
        togglzConsoleServlet.service(requestWrapper, response);
        return null;
    }

    private class DelegatingServletConfig implements ServletConfig {

        private final ServletContext servletContext;

        DelegatingServletConfig(final ServletContext servletContext) {
            this.servletContext = servletContext;
        }

        @Override
        public String getServletName() {
            return TogglzConsoleEndpoint.this.togglzConsoleServlet.getServletName();
        }

        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }

        @Override
        public String getInitParameter(final String name) {
            return servletContext.getInitParameter(name);
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return servletContext.getInitParameterNames();
        }
    }
}