我使用的是Drowpizard 0.7.1,但也许我很快会升级到0.8.4。
有没有人知道如何向dropwizard添加管理资源,这在操作菜单中显示,如下例所示?
Operational Menu
Metrics
Ping
Threads
Healthcheck
CustomAdminXy
答案 0 :(得分:8)
我认为你不能轻易做到这一点。
构建ServerFactory
时会创建AdminServlet
。可以扩展DefaultServerFactory
并覆盖createAdminServlet
以使用您的链接等创建自定义Admin servlet ...(然后您必须通过配置设置服务器工厂。)
似乎这会涉及一些代码重复,并且可能非常脆弱。
注册自己的管理servlet(除常规管理servlet之外)可能更容易,例如:
environment.admin().addServlet("custom-admin", new CustomAdminServlet())
.addMapping("/custom-admin");
可能也不理想。
答案 1 :(得分:3)
将.addMapping("")
与Dropwizard 0.9.1版一起使用,可以覆盖菜单,而不会与"/*"
处的默认AdminServlet映射冲突。
在申请表中:
public void run(final NetworkModelApplicationConfiguration configuration, final Environment environment) {
environment.admin().addServlet("my-admin-menu", new MyAdminServlet()).addMapping("");
environment.admin().addServlet("my-admin-feature", new MyAdminFeatureServlet()).addMapping("/myAdminFeature");
}
扩展AdminServlet并不是非常有用,因为所有属性都是私有的。我构建了一个HTTPServlet,它将资源作为模板读取:
public class MyAdminServlet extends HttpServlet {
private String serviceName;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.serviceName = config.getInitParameter("service-name");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getContextPath() + req.getServletPath();
resp.setStatus(200);
resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
try {
String template = getResourceAsString("/admin.html", "UTF-8");
String serviceName = this.serviceName == null?"":" (" + this.serviceName + ")";
writer.println(MessageFormat.format(template, new Object[] { path, serviceName }));
} finally {
writer.close();
}
}
String getResourceAsString(String resource, String charSet) throws IOException {
InputStream in = this.getClass().getResourceAsStream(resource);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
return out.toString(charSet);
}
}
我的/admin.html
资源如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Operational Menu{1}</title>
</head>
<body>
<h1>Operational Menu{1}</h1>
<ul>
<li><a href="{0}/metrics?pretty=true">Metrics</a></li>
<li><a href="{0}/ping">Ping</a></li>
<li><a href="{0}/threads">Threads</a></li>
<li><a href="{0}/healthcheck?pretty=true">Healthcheck</a></li>
<li><a href="{0}/myAdminFeature">My Admin Feature</a></li>
</ul>
</body>
</html>