Java 開発環境を設定する

このチュートリアルでは、Google Cloudで動作する Java アプリの開発など、Java 開発用にローカルマシンを準備する方法を説明します。Java と関連ツールをインストールする手順は次のとおりです。

目標

  • JDK(Java Development Kit)をインストールする
  • ビルド自動化ツールをインストールする
  • gcloud CLI をインストールする
  • (オプション)IDE またはエディタをインストールする
  • (省略可)IDE Google Cloud プラグインをインストールします。
  • Java 用 Cloud クライアント ライブラリをインストールする
  • 認証を設定する。

JDK(Java Development Kit)をインストールする

次の環境変数が設定されていることを確認することで、任意の Java ディストリビューションを選択できます。

  • JAVA_HOME: JDK インストールのベースを指します。
  • PATH: $JAVA_HOME/bin が含まれます。

Eclipse Temurin は、Google Cloudで使用する推奨の OpenJDK(Java 開発キット)ディストリビューションです。Temurin は、オープンソース ライセンスを取得し、Java SE TCK 認定を受けており、本番環境品質のパフォーマンスとセキュリティを確保するためにテストされています。

Temurin のインストール手順は、オペレーティング システムによって異なります。

Compute Engine ブートイメージを使用している場合は、次のインストール スクリプトを使用できます。

CentOS/RHEL/Rocky

  1. CentOS/RHEL/Rocky Linux のメジャー バージョンを特定します。
    eval "$(grep VERSION_ID /etc/os-release)"
    eval "$(grep ^ID= /etc/os-release)"
    OLD_IFS=$IFS
    IFS='.'
    read -ra split_version <<< "$VERSION_ID"
    IFS=$OLD_IFS
    MAJOR_VERSION=$split_version
  2. Adoptium ソース repo ファイル `/etc/yum.repos.d/adoptium.repo` を作成します。
    sudo tee /etc/yum.repos.d/adoptium.repo << EOM
    [Adoptium]
    name=Adoptium
    baseurl=https://packages.adoptium.net/artifactory/rpm/$ID/$MAJOR_VERSION/\$basearch
    enabled=1
    gpgcheck=1
    gpgkey=https://packages.adoptium.net/artifactory/api/gpg/key/public
    EOM
  3. パッケージ リストを更新します。
    sudo yum update -y
  4. Temurin をインストールします。
    sudo yum install -y temurin-17-jdk
  5. インストールを確認します。
    java -version

Debian、Ubuntu

  1. 公開リポジトリの GPG 鍵をインストールします。Ubuntu 16.4 を使用している場合は、ファイルに保存する前に gpg --dearmor を介して鍵を渡します。(例: sudo wget ... | gpg --dearmor | sudo tee ...
    sudo mkdir -p /etc/apt/keyrings
    sudo wget -O - https://packages.adoptium.net/artifactory/api/gpg/key/public |
      sudo tee /etc/apt/keyrings/adoptium.asc
  2. Linux ディストリビューションの名前を特定し、ソースリスト ファイル /etc/apt/sources.list.d/adoptium.list を作成します。
    eval "$(grep VERSION_CODENAME /etc/os-release)"
    sudo tee /etc/apt/sources.list.d/adoptium.list << EOM
    deb [signed-by=/etc/apt/keyrings/adoptium.asc] https://packages.adoptium.net/artifactory/deb $VERSION_CODENAME main
    EOM
  3. パッケージ リストを更新します。
    sudo apt update -y
  4. Temurin をインストールします。
    sudo apt install -y temurin-17-jdk
  5. インストールを確認します。
    java -version

SLES

  1. SLES のメジャー バージョンを確認します。
    eval "$(grep VERSION_ID /etc/os-release)"
    OLD_IFS=$IFS
    IFS='.'
    read -ra split_version <<< "$VERSION_ID"
    IFS=$OLD_IFS
    MAJOR_VERSION=$split_version
  2. 公開リポジトリの GPG 鍵をインストールします。
    sudo mkdir -p /etc/zypp/keyrings
    sudo wget -O - https://packages.adoptium.net/artifactory/api/gpg/key/public |
      sudo tee /etc/zypp/keyrings/adoptium.asc
    sudo rpm --import /etc/zypp/keyrings/adoptium.asc
  3. SLES のバージョンを特定し、Adoptium リポジトリを登録します。
    sudo zypper ar -f "https://packages.adoptium.net/artifactory/rpm/sles/$MAJOR_VERSION/$(uname -m)" adoptium
  4. パッケージ リストを更新します。
    sudo zypper update -y
  5. Temurin をインストールします。
    sudo zypper install -y temurin-17-jdk
  6. インストールを確認します。
    java -version

Windows

Temurin をインストールするには、次のコマンドを使用して PowerShell バージョン 3.0 以降を管理者として実行します。

  1. Temurin をダウンロードします。以下の手順の Invoke-WebRequest コマンドには、PowerShell 3.0 以降が必要です。
    $JdkVersion = 17
    $JdkUrl = "https://api.adoptium.net/v3/binary/latest/$JdkVersion/ga/windows/x64/jdk/hotspot/normal/eclipse?project=jdk"
    $JdkExtractionPath = "C:\temurin-$JdkVersion-jdk"
    $JdkDownload = "$JdkExtractionPath.zip"
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls12'
    Invoke-WebRequest -Uri $JdkUrl -OutFile $JdkDownload
    Expand-Archive $JdkDownload -DestinationPath $JdkExtractionPath -Force
  2. JAVA_HOME 変数と Path 変数を設定します。
    pushd $JdkExtractionPath
    $JdkPath = (Get-ChildItem).FullName
    popd
    [System.Environment]::SetEnvironmentVariable('JAVA_HOME', $JdkPath, 'Machine')
    
          
  3. (Optional) Refresh your session's `$env:Path` value. Otherwise, start a new session:
    $MachinePath = [System.Environment]::GetEnvironmentVariable('Path', 'Machine')
    $UserPath = [System.Environment]::GetEnvironmentVariable('Path', 'User')
    $env:Path = "$MachinePath;$UserPath"
  4. インストールを確認します。
    java -version

ビルド自動化ツールをインストールする

Apache MavenGradleSBTは、プラットフォーム間で迅速かつ一貫性のある Java アプリの依存関係を構築するのに役立つパッケージ管理オプションです。

gcloud CLI をインストールする

gcloud CLI は、 Google Cloudのための一連のツールです。このセットには gcloudbq が含まれており、Compute Engine、Cloud Storage、BigQuery などのプロダクトやサービスにコマンドラインからアクセスできます。これらのツールはインタラクティブに実行することも、自動スクリプトで実行することもできます。

(オプション)IDE またはエディタをインストールする

Java アプリの開発に広く使用されているエディタの一部を以下に示します(順不同)。

これらのエディタには、構文のハイライト表示、インテリセンス、コード補完から完全な統合デバッグ機能まで、豊富な機能が用意されています(プラグインが必要になる場合もあります)。

(オプション)IDE プラグインをインストールする

エディタ内の便利な機能にアクセスするには、次のプラグインを確認してください。

Java 用 Cloud クライアント ライブラリをインストールする

Java 用 Cloud クライアント ライブラリを使用して、Datastore や Cloud Storage などの Google Cloudサービスと統合します。次の例に示すように、BigQuery などの個別の API のパッケージをインストールできます。

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<!--  Using libraries-bom to manage versions.
See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.62.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-bigquery</artifactId>
  </dependency>
</dependencies>

If you are using Gradle, add the following to your dependencies:

implementation platform('com.google.cloud:libraries-bom:26.45.0')

implementation 'com.google.cloud:google-cloud-bigquery'

If you are using sbt, add the following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-bigquery" % "2.42.2"

If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

認証を設定する

クライアント ライブラリを実行するには、まず認証を設定する必要があります。

If you're using a local shell, then create local authentication credentials for your user account:

gcloud auth application-default login

You don't need to do this if you're using Cloud Shell.

If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

詳細については、クライアント ライブラリを使用して認証するをご覧ください。

クライアント ライブラリの使用

// Imports the Google Cloud client library
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetInfo;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiate a client. If you don't specify credentials when constructing a client, the
    // client library will look for credentials in the environment, such as the
    // GOOGLE_APPLICATION_CREDENTIALS environment variable.
    BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

    // The name for the new dataset
    String datasetName = "my_new_dataset";

    // Prepares a new dataset
    Dataset dataset = null;
    DatasetInfo datasetInfo = DatasetInfo.newBuilder(datasetName).build();

    // Creates the dataset
    dataset = bigquery.create(datasetInfo);

    System.out.printf("Dataset %s created.%n", dataset.getDatasetId().getDataset());
  }
}

クライアント ライブラリのエンドポイントを構成する

リージョン エンドポイントをサポートする API を使用する場合は、エンドポイントを使用して、リクエストの送信先サーバーを構成します。たとえば、Google.Cloud.Dataproc.V1 API を使用して、クライアント エンドポイントを構成できます。Dataproc のリージョン エンドポイントの詳細については、こちらをご覧ください。次の例では、MY-PROJECT はプロジェクト名に、us-central1 は構成に適したリージョンに置き換えてください。

ClusterControllerSettings settings =
     ClusterControllerSettings.newBuilder()
        .setEndpoint("us-central1-dataproc.googleapis.com:443")
        .build();
 try (ClusterControllerClient clusterControllerClient = ClusterControllerClient.create(settings)) {
   String projectId = "MY-PROJECT";
   String region = "us-central1";
   Cluster cluster = Cluster.newBuilder().build();
 }

次のステップ

(オプション)App Engine 用の Maven プラグインまたは Gradle プラグインを使用する

App Engine スタンダード環境またはフレキシブル環境で開発している場合は、Apache Maven と Gradle ビルドツールの両方に対し、アプリケーションを直接開発、テスト、およびデプロイするための便利な機能を提供するプラグインを使用できます。

App Engine スタンダード環境の場合

App Engine スタンダード環境用の Maven App Engine プラグインまたは Gradle プラグインを使用します。

App Engine フレキシブル環境の場合

App Engine フレキシブル環境用の Maven App Engine プラグインまたは Gradle プラグインを使用します。

その他のリソース