Dropwizard:如何以编程方式停止服务

要启动该服务,我知道一个使用new MyService().run(args) 。 怎么阻止它?

我需要在我的测试中以编程方式启动和停止setUp()tearDown()

您可以在新线程中启动服务,一旦测试结束,服务将自动关闭。

但是从dropwizard 0.6.2开始,dropwizard-testing模块包含一个完全符合此用例的junit规则 ( 参见此处 )。

此规则的用法如下所示:

 Class MyTest { @ClassRule public static TestRule testRule = new DropwizardServiceRule(MyService.class, Resources.getResource("service.yml").getPath())); @Test public void someTest(){ .... 

保持environment变量并将以下方法添加到您的应用程序:

 public void stop() throws Exception { environment.getApplicationContext().getServer().stop(); } 

现在,您可以调用myService.stop()来停止服务器。

谢谢@LiorH这个伟大的建议。

这是一个使用dropwizard-0.6.2中的DropwizardServiceRule的完整测试类。

首先创建一个用于测试的服务配置: testing-server.yml并将其放在测试的类路径中(例如src\test\resources )。 这样,您可以为要使用的测试服务设置不同的端口:

 http: port: 7000 adminPort: 7001 

检查“/ request”位置是否有资源的简单测试类如下所示:

 class TheServiceTest { @ClassRule public static DropwizardServiceRule RULE = new DropwizardServiceRule(TheService.class, Resources.getResource("testing-server.yml").getPath()); @Test public void dropwizard_gets_configured_correctly() throws Exception { Client client = new Client(); ClientResponse response = client.resource( String.format("http://localhost:%d/request", RULE.getLocalPort())) .get(ClientResponse.class); assertThat(response.getStatus(), is(200)); } } 

我还添加了导入,以防您不知道要选择哪种实现。

 import com.google.common.io.Resources; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.yammer.dropwizard.testing.junit.DropwizardServiceRule; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TestRule; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; 

在测试结束时,服务器将正常关闭,因此您无需担心它。

你可以尝试使用org.eclipse.jetty.server.Server的stop()方法,该方法由Dropwizard内部使用。

或者你在main / constructor中使用这个java特性……:

  // In case jvm shutdown Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // what should be closed if forced shudown // .... LOG.info(String.format("--- End of ShutDownHook (%s) ---", APPLICATION_NAME)); } });