用Dropwizard与Spark的Java服务进行对话

84 阅读2分钟

前几天,我们在工作中就DropwizardSpark的Java服务进行了一次对话。我的一个同事喜欢Spark的简单性,特别是在构建示例应用程序时。我指出,Dropwizard也可以很简单,但他们的入门指南让人很难意识到这一点。它经历了很多对生产服务很重要的步骤,但在我看来,这不应该是最初入门指南的一部分。因此,我决定展示一个简单的Dropwizard应用程序是什么样子,没有所有的东西。

我的例子没有配置类,没有配置文件,没有健康检查,没有表示类,等等。但是,如果有必要的话,以后再添加这些东西就很容易了,而不是一开始就把所有东西都加进去。

整个应用程序只有两个Java文件和一个pom.xml 。Java文件被分成了应用程序(包括主方法)和资源(即路由)。这里是最基本的应用程序。

public class DropwizardExampleApplication extends Application<Configuration> {
  public static void main(String[] args) throws Exception {
    new DropwizardExampleApplication().run(args);
  }

  @Override
  public void run(Configuration configuration, Environment environment) {
    environment.jersey().register(new Resource());
  }
}

正如你所看到的,你真正需要的是一个调用run 和行来注册资源的主方法。运行Dropwizard的首选方式是通过打包的jars。

% mvn package && java -jar target/dropwizard-example-1.0-SNAPSHOT.jar server

你也可以直接从IDE中运行主方法以方便迭代。

资源也可以是超级简单的。例如,这里是一个简单的GET路由的样子。

@Path("/")
public class Resource {
  @GET
  @Path("/hello")
  public String hello() {
    return "Hello";
  }
}
% curl localhost:8080/hello
Hello

方法被注释为@Path ,Dropwizard(Jersey)做剩下的事情。如果你想要查询参数,你只需注解方法参数。

  @GET
  @Path("/query")
  public String query(@QueryParam("message") String message) {
    return "You passed " + message;
  }
% curl 'localhost:8080/query?message=hello'
You passed hello

一个不同的注释可以给你提供表单参数。

  @POST
  @Path("/postparam")
  public String postParam(@FormParam("message") String message) {
    return "You posted " + message;
  }
% curl -X POST -d 'message=hello' localhost:8080/postparam
You posted hello

对于一般的POST体,你甚至不需要注解。

  @POST
  @Path("/postbody")
  public String postBody(String message) {
    return "You posted " + message;
  }
% curl -X POST -d 'hello' localhost:8080/postbody
You posted hello

对于更复杂的POST,你可能想使用一个表示类。但是对于一个简单的例子来说,我认为字符串是非常容易的。

总而言之,它不像Spark那么简单,但我认为它很接近。

整个项目都在GitHub上:https://github.com/pgr0ss/dropwizard-example