1. 概述
Dropwizard 是一個開源 Java 框架,用於快速開發高性能的 RESTful Web 服務。它彙集了一些流行的庫,以創建一個輕量級軟件包。它主要使用 Jetty、Jersey、Jackson、JUnit 和 Guava 等庫。此外,它還使用自己的庫 Metrics。
在本教程中,我們將學習如何配置和運行一個簡單的 Dropwizard 應用程序。完成之後,我們的應用程序將暴露一個 RESTful API,允許我們獲取存儲的品牌列表。
2. Maven 依賴
首先,dropwizard-core 依賴項是我們創建服務的全部需求。下面我們將其添加到我們的 pom.xml 中:
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>2.0.0</version>
</dependency>3. 配置
現在,我們將創建所需的類,以便每個 Dropwizard 應用程序都能正常運行。
Dropwizard 應用程序使用 YML 文件存儲屬性。因此,我們將創建 introduction-config.yml 文件在資源目錄中:
defaultSize: 5我們可以通過創建擴展 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 將配置文件的內容反序列化為我們的類。因此,我們使用了 Jackson 的註解。
接下來,讓我們創建一個主應用程序類,該類負責為服務的使用做好準備:
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) {
//register classes
}
@Override
public void initialize(Bootstrap<BasicConfiguration> bootstrap) {
bootstrap.setConfigurationSourceProvider(new ResourceConfigurationSourceProvider());
super.initialize(bootstrap);
}
}首先,main 方法負責運行應用程序。我們可以將 args 傳遞給 run 方法,或者手動填寫它。
第一個參數可以是 server 或 check。 check 選項驗證配置,而 server 選項運行應用程序。 第二個參數是配置文件的位置。
此外,initialize 方法將配置提供程序設置為 ResourceConfigurationSourceProvider,這允許應用程序在資源目錄中找到給定的配置文件。 覆蓋此方法並非必需。
最後,run 方法允許我們訪問 Environment 和 BaseConfiguration,我們將會在本文稍後使用它們。
4. 資源
首先,讓我們為我們的品牌創建一個領域模型:
public class Brand {
private final Long id;
private final String name;
// all args constructor and getters
}其次,我們創建一個 BrandRepository 類,該類將負責返回品牌:
public class BrandRepository {
private final List<Brand> brands;
public BrandRepository(List<Brand> brands) {
this.brands = ImmutableList.copyOf(brands);
}
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();
}
}此外,我們還使用了來自 Guava 的 ImmutableList,因為它本身就是 Dropwizard 的一部分。
第三,我們將創建一個 BrandResource 類。 Dropwizard 默認使用 JAX-RS,Jersey 作為實現。因此,我們將使用該規範中的註解來暴露我們的 REST API 端點:
@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);
}
}此外,我們已將 尺寸 定義為 可選,以便在未提供參數時,使用來自配置的 默認尺寸。
最後,我們將 品牌資源 註冊到 介紹應用程序 類中。為此,讓我們實現 運行 方法:
@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. 運行應用程序
本節將介紹如何從命令行運行應用程序。
首先,我們將配置項目以使用 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>這是插件的建議配置。此外,我們還將在 <mainClass> 元素中包含了指向我們主類的路徑。
最後,我們將使用 Maven 構建應用程序。獲得 JAR 文件後,我們可以運行應用程序:
java -jar target/dropwizard-0.0.1-SNAPSHOT.jar無需傳遞參數,因為我們已經將它們包含在 IntroductionApplication 類中。
之後,控制枱日誌應該以以下內容結尾:
INFO [2020-01-08 18:55:06,527] org.eclipse.jetty.server.Server: Started @1672ms現在,應用程序正在監聽 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此配置設置應用程序在 9090 端口上運行,管理員界面在 9091 端口上運行。可以通過將配置文件的內容傳遞給 run()方法來應用此配置。
// ...
new IntroductionApplication().run("server", "introduction-config.yml");
// ...此外,啓動應用程序時,還可以通過命令行應用配置文件:
$ java -jar target/dropwizard-0.0.1-SNAPSHOT.jar server introduction-config.yml
在上述命令中,我們使用 server 和 introduction-config.yml 參數啓動應用程序。
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
-Ddw 前綴定義了 Dropwizard 特定的系統屬性,用於設置主應用程序端口和管理界面端口。 這些系統屬性如果指定,將覆蓋配置文件的設置。 如果未定義系統屬性,則使用配置文件的值。
7. 健康檢查
啓動應用程序時,我們得知應用程序中沒有健康檢查。 幸運的是,Dropwizard 提供了一個簡單易用的解決方案,可以為我們的應用程序添加健康檢查。
讓我們首先添加一個擴展 com.codahale.metrics.health.HealthCheck 的類:
public class ApplicationHealthCheck extends HealthCheck {
@Override
protected Result check() throws Exception {
return Result.healthy();
}
}這種簡單的方法將返回我們組件的健康狀況信息。我們可以創建多個健康檢查,其中一些在特定情況下可能會失敗。例如,如果數據庫連接失敗,我們將返回 Result.unhealthy()。
最後,我們需要在 IntroductionApplication 類的 run 方法中 註冊我們的健康檢查:
environment
.healthChecks()
.register("application", new ApplicationHealthCheck());在運行應用程序後,我們可以檢查健康檢查響應,位於 http://localhost:8081/healthcheck 下:
{
"application": {
"healthy": true,
"duration": 0
},
"deadlocks": {
"healthy": true,
"duration": 0
}
}如我們所見,我們的健康檢查已註冊在 application 標籤下。
8. 結論
在本文中,我們學習瞭如何使用 Maven 設置 Dropwizard 應用程序。
我們發現應用程序的基礎設置非常簡單快捷。 此外,Dropwizard 包含了我們運行高性能 RESTful Web 服務的所需的所有庫。