问题
To start the service, I know one uses new MyService().run(args)
. How to stop it?
I need to start and stop programmatically for setUp()
and tearDown()
in my tests.
回答1:
You can start the service in new thread, once the test ends the service will shutdown automatically.
However starting in dropwizard 0.6.2 the dropwizard-testing module contains a junit rule exactly for this use case (see here).
Usage of this rule will look something like this:
Class MyTest {
@ClassRule
public static TestRule testRule = new DropwizardServiceRule<MyConfiguration>(MyService.class,
Resources.getResource("service.yml").getPath()));
@Test
public void someTest(){
....
回答2:
Keep the environment
variable around and add the following method to your application:
public void stop() throws Exception {
environment.getApplicationContext().getServer().stop();
}
Now you can call myService.stop()
to stop the server.
回答3:
Thanks @LiorH for this great suggestion.
Here is a complete test class using the DropwizardServiceRule in dropwizard-0.6.2.
First create a service configuration for testing: testing-server.yml
and place it in the test's class path (ex. src\test\resources
).
This way you can set different ports for the test service to use:
http:
port: 7000
adminPort: 7001
A simple test class that checks if there is a resource at the location "/request" looks like this:
class TheServiceTest {
@ClassRule
public static DropwizardServiceRule RULE = new DropwizardServiceRule<MyConfiguration>(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));
}
}
I have also added the import in case you do not know what implementation to choose.
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;
At the end of the tests, the server will shutdown gracefully, so you do not need to worry about it.
回答4:
you can try using stop() method of org.eclipse.jetty.server.Server, which is internally used by Dropwizard.
回答5:
Or you use this java feature in your main/constructor ...:
// 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));
}
});
来源:https://stackoverflow.com/questions/15989008/dropwizard-how-to-stop-service-programmatically