1. 概要

Dropwizardは、高性能のRESTfulWebサービスの高速開発に使用されるオープンソースのJavaフレームワークです。 いくつかの人気のあるライブラリを集めて、軽量パッケージを作成します。 使用する主なライブラリは、Jetty、Jersey、Jackson、JUnit、およびGuavaです。 さらに、Metricsと呼ばれる独自のライブラリを使用します。

このチュートリアルでは、単純なDropwizardアプリケーションを構成して実行する方法を学習します。 完了すると、アプリケーションは、保存されているブランドのリストを取得できるRESTfulAPIを公開します。

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メソッドがアプリケーションの実行を担当します。 argsrunメソッドに渡すか、自分で入力することができます。

最初の引数はserverまたはcheckのいずれかです。check オプションは構成を検証し、serverオプションはアプリケーションを実行します。 2番目の引数は、構成ファイルの場所です。 

さらに、 initialize メソッドは、構成プロバイダーを ResourceConfigurationSourceProvider に設定します。これにより、アプリケーションはリソースディレクトリ内の特定の構成ファイルを見つけることができます。 このメソッドをオーバーライドする必要はありません。

最後に、 run メソッドを使用すると、EnvironmentBaseConfigurationの両方にアクセスできます。これらはこの記事の後半で使用します。

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

さらに、 Dropwizard自体の一部であるため、GuavaのImmutableListを使用できました。

3番目に、BrandResourceクラスを作成します。 Dropwizardは、実装としてJerseyを使用してデフォルトでJAX-RSを使用します。 したがって、この仕様のアノテーションを利用して、RESTAPIエンドポイントを公開します。

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

さらに、引数が指定されていない場合に構成から defaultSize を使用するために、sizeOptionalとして定義しました。

最後に、BrandResourceIntroductionApplicatonクラスに登録します。 そのために、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. 実行中のアプリケーション

このセクションでは、コマンドラインからアプリケーションを実行する方法を学習します。

まず、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>

これは、プラグインの推奨構成です。 さらに、メインクラスへのパスをエレメント。

最後に、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は、アプリケーションにヘルスチェックを追加するための簡単なソリューションを提供します。

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タグで登録されています。

7. 結論

この記事では、Mavenを使用してDropwizardアプリケーションをセットアップする方法を学びました。

アプリケーションの基本セットアップが非常に簡単で高速であることを発見しました。 さらに、Dropwizardには、高性能のRESTfulWebサービスを実行するために必要なすべてのライブラリが含まれています。

いつものように、これらの例のコードはGitHubから入手できます。