简单几步使用Dropwizard实现一个RESTful微服务

Dropwizard是一个轻量实现Java微服务的框架,官方案例可能比较复杂,这里展示分分钟简单几步实现一个RESTful微服务。

整个应用只有两个Java文件和pom.xml,Java文件分成带有main方法的应用主文件和资源如路由等,主应用文件代码如下:


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());
}
}

正如你看到,所有需要做的就是在main方法中调用run,而其主要是注册资源。运行Dropwizard通过其jar包:
mvn package && java -jar target/dropwizard-example-1.0-SNAPSHOT.jar server

资源也很简单,比如下面是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参数如下:


@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

整个项目源码见: Github

Dropwizard Can Be Simple