OSSClientは、Object Storage Service (OSS) のJavaクライアントです。 バケットやオブジェクトなどのOSSリソースの管理に使用されます。 OSS SDK for Javaを使用してリクエストを開始するには、OSSClientインスタンスを初期化し、ビジネス要件に基づいてClientConfiguration設定クラスのデフォルト設定項目を変更する必要があります。
使用上の注意
OSSClientインスタンスを初期化する前に、アクセス資格情報を設定する必要があります。 このトピックでは、アクセス資格情報は環境変数から取得します。 詳細については、「アクセス資格情報の設定」をご参照ください。
OSSでサポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。
RAM (Resource Access Management) ユーザーのAccessKeyペアを作成する方法については、「RAMユーザーのAccessKeyペアの作成」をご参照ください。
OSS SDK for Java 3.17.4以降を使用して、V4署名アルゴリズムをサポートします。 詳細については、「SDKのインストール」をご参照ください。
前提条件
クライアントを設定する前に、RAMユーザーのAccessKeyペアを使用して環境変数を設定する必要があります。
Linux
CLIで次のコマンドを実行して、環境変数の設定を
~/.bashrc
ファイルに追加します。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
次のコマンドを実行して変更を適用します。
source ~/.bashrc
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
ターミナルで次のコマンドを実行して、デフォルトのシェルタイプを表示します。
echo $SHELL
デフォルトのシェルタイプに基づいて環境変数を設定します。
Zsh
次のコマンドを実行して、環境変数の設定を
~/.zshrc
ファイルに追加します。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
次のコマンドを実行して変更を適用します。
source ~/.zshrc
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
バッシュ
次のコマンドを実行して、環境変数の設定を
~/.bash_profile
ファイルに追加します。echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
次のコマンドを実行して変更を適用します。
source ~/.bash_profile
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
CMDで次のコマンドを実行します。
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
次のコマンドを実行して、環境変数が有効かどうかを確認します。
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
PowerShellで次のコマンドを実行します。
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
次のコマンドを実行して、環境変数が有効かどうかを確認します。
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
デフォルトの設定例
このセクションでは、V4署名アルゴリズムとV1署名アルゴリズムを使用してOSSClientインスタンスを設定する方法の例を示します。
次のサンプルコードでは、バケットのパブリックエンドポイントとRAMユーザーのAccessKeyペアが使用されていることに注意してください。
(推奨しない) V1署名アルゴリズムを使用してOSSClientインスタンスを設定する
一般的なシナリオの設定例
このセクションでは、他のタイプのエンドポイントを使用してOSSClientインスタンスを構成する方法の例を示します。 サンプルコードでは、V4署名アルゴリズムとRAMユーザーのAccessKeyペアが使用されています。
内部エンドポイントを使用したOSSClientインスタンスの設定
アプリケーションがElastic Compute Service (ECS) インスタンスにデプロイされており、ECSインスタンスと同じリージョンのバケット内のOSSデータに頻繁にアクセスする必要がある場合は、内部エンドポイントを使用してネットワークの遅延と帯域幅のコストを大幅に削減します。
次のサンプルコードは、内部エンドポイントを使用してOSSClientインスタンスを構成する方法の例を示しています。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou-internal.aliyuncs.com.
String endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";
// Specify the region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
カスタムドメイン名を使用したOSSClientインスタンスの設定
使用量が異なる複数のバケットがある場合は、各バケットに異なるサブドメインを指定して、リソースをより適切に管理および整理できます。
次のサンプルコードは、カスタムドメイン名を使用してOSSClientインスタンスを構成する方法の例を示しています。
最初に、カスタムドメイン名をバケットのデフォルトドメイン名にマップする必要があります。 それ以外の場合は、エラーが返されます。 カスタムドメイン名をバケットのデフォルトドメイン名にマップする方法については、「カスタムドメイン名をバケットのデフォルトドメイン名にマップする」をご参照ください。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify a custom domain name. Example: https://static.example.com.
String endpoint = "https://static.example.com";
// Specify the region of the bucket. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Note: To enable CNAME, set this parameter to true.
clientBuilderConfiguration.setSupportCname(true);
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
プライベートドメインを使用したOSSClientインスタンスの設定
次のサンプルコードは、プライベートドメインを使用してOSSClientインスタンスを構成する方法の例を示しています。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify a private domain. Example: https://service.corp.example.com.
String endpoint = "https://service.corp.example.com";
// Specify the region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
IPアドレスを使用したOSSClientインスタンスの設定
次のサンプルコードは、IPアドレスを使用してOSSClientインスタンスを設定する方法の例を示しています。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify an IP address as the endpoint based on your business requirements.
String endpoint = "https://10.10.10.10";
// Specify the region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Enable access from a second-level domain. By default, access from second-level domains is disabled. OSS SDK for Java 2.1.2 or later automatically detects IP addresses. If you use OSS SDK for Java whose version is earlier than 2.1.2, you must specify this parameter.
clientBuilderConfiguration.setSLDEnabled(true);
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
プロキシサーバーを使用したOSSClientインスタンスの設定
次のサンプルコードは、プロキシサーバーを使用してOSSClientインスタンスを構成する方法の例を示しています。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class Demo {
public static void main(String[] args) throws Exception {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create the ClientBuilderConfiguration class.
// ClientBuilderConfiguration is a configuration class of an OSSClient instance. You can use the ClientBuilderConfiguration class to configure parameters, such as proxies, connection timeout period, and the maximum number of connections.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Specify User-Agent in the HTTP header. Default value: aliyun-sdk-java.
conf.setUserAgent("aliyun-sdk-java");
// Specify the IP address of the proxy server. Replace <yourProxyHost> with the IP address of the proxy server. Example: 196.128.xxx.xxx.
conf.setProxyHost("<yourProxyHost>");
// Specify the username verified by the proxy server. Replace <yourProxyUserName> with the username of the proxy server. Example: root.
conf.setProxyUsername("<yourProxyUserName>");
// Specify the password verified by the proxy server. Replace <yourProxyPassword> with the password of the user.
conf.setProxyPassword("<yourProxyPassword>");
// Create an OSSClient instance.
conf.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(conf)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
OSSClientインスタンスのタイムアウト期間の設定
次のサンプルコードは、OSSClientインスタンスのタイムアウト期間を設定する方法の例を示しています。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class Demo {
public static void main(String[] args) throws Exception {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create the ClientBuilderConfiguration class.
// ClientBuilderConfiguration is a configuration class of an OSSClient instance. You can use the ClientBuilderConfiguration class to configure parameters, such as proxies, connection timeout period, and the maximum number of connections.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// Specify the maximum number of HTTP connections that are allowed. If you do not specify this parameter, the default value 1024 is used.
conf.setMaxConnections(1024);
// Specify the timeout period for data transmission at the socket layer. Unit: milliseconds. If you do not specify this parameter, the default value 50000 is used.
conf.setSocketTimeout(50000);
// Specify the timeout period for establishing a connection. Unit: milliseconds. If you do not specify this parameter, the default value 50000 is used.
conf.setConnectionTimeout(50000);
// Specify the timeout period for obtaining a connection from the connection pool. Unit: milliseconds. If you do not specify this parameter, the timeout period is unlimited.
conf.setConnectionRequestTimeout(60*60*24*1000);
// Specify the timeout period for idle connections. The connection is closed when the timeout period ends. Unit: milliseconds. If you do not specify this parameter, the default value 60000 is used.
conf.setIdleConnectionTime(60000);
// Create an OSSClient instance.
conf.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(conf)
.region(region)
.build();
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
OSSClientインスタンスの設定方法
ClientConfigurationは、OSSClientインスタンスの構成クラスです。 ClientConfigurationクラスを使用して、プロキシ、接続タイムアウト期間、OSSClientインスタンスの最大接続数などのパラメーターを設定できます。
課金方法 | 説明 |
ClientConfiguration.setMaxConnections | 許可されるHTTP接続の最大数。 デフォルト値: 1024。 |
ClientConfiguration.setSocketTimeout | ソケット層でのデータ送信のタイムアウト期間。 単位はミリ秒です。 デフォルト値: 50000 |
ClientConfiguration.setConnectionTimeout | 接続を確立するためのタイムアウト期間。 単位はミリ秒です。 デフォルト値: 50000 |
ClientConfiguration.setConnectionRequestTimeout | 接続プールから接続を取得するためのタイムアウト時間。 単位はミリ秒です。 デフォルトでは、タイムアウト期間は指定されていません。 |
ClientConfiguration.setIdleConnectionTime | アイドル接続のタイムアウト期間。 タイムアウト期間が終了すると、接続は閉じられます。 単位はミリ秒です。 デフォルト値: 60000 説明 |
ClientConfiguration.setSupportCname | CNAME をエンドポイントとして使用できるかどうかを指定します。 デフォルトでは、CNAMEをエンドポイントとして使用できます。 |
ClientConfiguration.setCrcCheckEnabled | 巡回冗長検査 (CRC) 検証を有効にするかどうかを指定します。 デフォルトでは、CRC検証は有効です。 |
ClientConfiguration.setSLDEnabled | 第2レベルドメインからのアクセスを有効にするかどうかを指定します。 デフォルトでは、第2レベルドメインからのアクセスは無効になっています。 |
ClientConfiguration.setProtocol | OSSへの接続に使用されるプロトコル。 デフォルト値: HTTP。 有効な値は HTTP および HTTPS です。 |
ClientConfiguration.setUserAgent | ユーザーエージェント (HTTPヘッダーのuser-agentフィールド) 。 デフォルト値: |
ClientConfiguration.setProxyHost | プロキシサーバーへのアクセスに使用されるホストのIPアドレス。 |
ClientConfiguration.setProxyPort | プロキシサーバーへの接続に使用されるポート。 |
ClientConfiguration.setProxyUsername | プロキシサーバーへのログオンに使用されるユーザー名。 |
ClientConfiguration.setProxyPassword | プロキシサーバーへのログインに使用されるパスワード。 |
ClientConfiguration.setRedirectEnable | HTTPリダイレクトを有効にするかどうかを指定します。 説明 OSS SDK for Java 3.10.1以降のHTTPリダイレクトを有効にするかどうかを指定できます。 デフォルトでは、OSS SDK for Java 3.10.1以降でHTTPリダイレクトが有効になっています。 |
ClientConfiguration.setVerifySSLEnable | SSLベースの認証を有効にするかどうかを指定します。 説明 OSS SDK for Java 3.10.1以降のSSLベースの認証を有効にするかどうかを指定できます。 OSS SDK for Java 3.10.1以降では、デフォルトでSSLベースの認証が有効になっています。 |
ClientConfiguration.setMaxErrorRetry | リクエストエラー発生時の最大リトライ回数。 デフォルト値:3 説明 エラーが発生すると、OSSはリクエストタイプごとに異なる再試行ポリシーを使用します。
|
ClientConfiguration.setRetryStrategy() | カスタム再試行ポリシー。 ほとんどの場合、カスタム再試行ポリシーを指定しないことをお勧めします。 |