1. 概述
Dropwizard 是一个开源的 Java 框架,专为快速构建高性能的 RESTful 服务而设计。它整合了多个成熟的第三方库,打包成一个轻量级的开发套件。核心依赖包括 Jetty(嵌入式 Web 服务器)、Jersey(JAX-RS 实现)、Jackson(JSON 处理)、JUnit(测试)和 Guava(工具库),同时还集成了自家的 Metrics 库用于监控。
本文将带你从零搭建一个简单的 Dropwizard 应用,最终实现一个可通过 RESTful 接口获取品牌列表的服务。
2. Maven 依赖
要使用 Dropwizard,只需引入 dropwizard-core
依赖即可:
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>2.0.0</version>
</dependency>
✅ 这个依赖已经包含了 Jetty、Jersey、Jackson 等常用库,开箱即用,省去了手动整合的麻烦。
3. 配置管理
每个 Dropwizard 应用都需要配置类和 YAML 配置文件。
3.1 配置文件
在 resources
目录下创建 introduction-config.yml
:
defaultSize: 5
3.2 配置类
创建一个继承 io.dropwizard.Configuration
的类,用于映射配置:
public class BasicConfiguration extends Configuration {
@NotNull private final int defaultSize;
@JsonCreator
public BasicConfiguration(@JsonProperty("defaultSize") int defaultSize) {
this.defaultSize = defaultSize;
}
public int getDefaultSize() {
return defaultSize;
}
}
⚠️ 注意:Dropwizard 使用 Jackson 解析 YAML,因此需要 Jackson 注解(如 @JsonProperty
)来绑定字段。
3.3 主应用类
public class IntroductionApplication extends Application<BasicConfiguration> {
public static void main(String[] args) throws Exception {
new IntroductionApplication().run("server", "introduction-config.yml");
}
@Override
public void run(BasicConfiguration basicConfiguration, Environment environment) {
// 注册资源、健康检查等
}
@Override
public void initialize(Bootstrap<BasicConfiguration> bootstrap) {
bootstrap.setConfigurationSourceProvider(new ResourceConfigurationSourceProvider());
super.initialize(bootstrap);
}
}
关键点说明:
main
方法启动应用,参数:- 第一个参数为
server
(启动服务)或check
(校验配置) - 第二个参数是配置文件路径
- 第一个参数为
initialize
方法中设置ResourceConfigurationSourceProvider
,让应用能从 classpath 加载配置文件(非必须)run
方法提供Environment
和Configuration
实例,后续注册组件要用
4. 资源与接口实现
4.1 领域模型
public class Brand {
private final Long id;
private final String name;
// 全参构造 + Getter(略)
}
4.2 数据访问层
public class BrandRepository {
private final List<Brand> brands;
public BrandRepository(List<Brand> brands) {
this.brands = ImmutableList.copyOf(brands); // ✅ 使用 Guava 的不可变集合
}
public List<Brand> findAll(int size) {
return brands.stream()
.limit(size)
.collect(Collectors.toList());
}
public Optional<Brand> findById(Long id) {
return brands.stream()
.filter(brand -> brand.getId().equals(id))
.findFirst();
}
}
✅ Dropwizard 内置 Guava,可以直接使用 ImmutableList
,避免外部依赖。
4.3 REST 接口
@Path("/brands")
@Produces(MediaType.APPLICATION_JSON)
public class BrandResource {
private final int defaultSize;
private final BrandRepository brandRepository;
public BrandResource(int defaultSize, BrandRepository brandRepository) {
this.defaultSize = defaultSize;
this.brandRepository = brandRepository;
}
@GET
public List<Brand> getBrands(@QueryParam("size") Optional<Integer> size) {
return brandRepository.findAll(size.orElse(defaultSize));
}
@GET
@Path("/{id}")
public Brand getById(@PathParam("id") Long id) {
return brandRepository
.findById(id)
.orElseThrow(RuntimeException::new);
}
}
关键点:
- 使用 JAX-RS 注解(
@Path
,@GET
,@QueryParam
等)定义接口 size
参数为Optional
,未传时使用配置中的defaultSize
- 返回 JSON 格式(
@Produces
指定)
4.4 注册资源
在 IntroductionApplication
的 run
方法中注册:
@Override
public void run(BasicConfiguration basicConfiguration, Environment environment) {
int defaultSize = basicConfiguration.getDefaultSize();
BrandRepository brandRepository = new BrandRepository(initBrands());
BrandResource brandResource = new BrandResource(defaultSize, brandRepository);
environment
.jersey()
.register(brandResource); // ✅ 所有资源都要在这里注册
}
5. 启动应用
5.1 打包配置
使用 maven-shade-plugin
构建可执行 JAR:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.baeldung.dropwizard.introduction.IntroductionApplication</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
5.2 运行
mvn package
java -jar target/dropwizard-0.0.1-SNAPSHOT.jar server introduction-config.yml
✅ 输出日志中出现 Started @xxxms
表示启动成功。
服务默认监听 8080 端口,访问 http://localhost:8080/brands
即可获取品牌列表。
6. 修改默认端口
Dropwizard 默认使用两个端口:
8080
:应用接口8081
:管理接口(健康检查、指标等)
6.1 配置文件方式
修改 introduction-config.yml
:
server:
applicationConnectors:
- type: http
port: 9090
adminConnectors:
- type: http
port: 9091
然后启动时指定配置文件即可。
6.2 命令行方式(推荐)
直接通过 JVM 参数覆盖:
java -Ddw.server.applicationConnectors[0].port=9090 \
-Ddw.server.adminConnectors[0].port=9091 \
-jar target/dropwizard-0.0.1-SNAPSHOT.jar server
✅ 命令行参数优先级高于配置文件,适合不同环境快速切换。
7. 健康检查
启动时日志会提示“no health checks”,我们来加一个。
7.1 实现健康检查
public class ApplicationHealthCheck extends HealthCheck {
@Override
protected Result check() throws Exception {
return Result.healthy();
}
}
实际项目中可检查数据库、缓存等依赖。
7.2 注册健康检查
在 run
方法中注册:
environment
.healthChecks()
.register("application", new ApplicationHealthCheck());
✅ 注册后访问 http://localhost:8081/healthcheck
查看结果:
{
"application": {
"healthy": true,
"duration": 0
},
"deadlocks": {
"healthy": true,
"duration": 0
}
}
8. 总结
Dropwizard 通过整合主流库,让 RESTful 服务开发变得简单粗暴。几行配置 + 注解就能跑起来,适合快速交付的项目。其内置的 Metrics 和健康检查机制也方便后期运维。
文中示例代码已托管至 GitHub:https://github.com/eugenp/tutorials/tree/master/web-modules/dropwizard