alibabacloud-sdk-client-initialization-for-java

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Client Initialization Best Practices (Java)

Java客户端初始化最佳实践

Core Rules

核心规则

  • Client is thread-safe — safe to share across threads without synchronization.
  • Use singleton pattern — do NOT create new client instances per request. Frequent
    new Client()
    calls waste resources and hurt performance.
  • Prefer explicit endpoint over region-based endpoint resolution.
  • 客户端是线程安全的——无需同步即可在多线程间共享。
  • 使用单例模式——不要为每个请求创建新的客户端实例。频繁调用
    new Client()
    会浪费资源并影响性能。
  • 优先使用显式指定Endpoint,而非基于Region的Endpoint自动解析。

Recommended Client Creation

推荐的客户端创建方式

java
public class ClientFactory {
    private static volatile com.aliyun.ecs20140526.Client instance;

    public static com.aliyun.ecs20140526.Client getInstance() throws Exception {
        if (instance == null) {
            synchronized (ClientFactory.class) {
                if (instance == null) {
                    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                        .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                        .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                    config.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
                    instance = new com.aliyun.ecs20140526.Client(config);
                }
            }
        }
        return instance;
    }
}
java
public class ClientFactory {
    private static volatile com.aliyun.ecs20140526.Client instance;

    public static com.aliyun.ecs20140526.Client getInstance() throws Exception {
        if (instance == null) {
            synchronized (ClientFactory.class) {
                if (instance == null) {
                    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                        .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                        .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                    config.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
                    instance = new com.aliyun.ecs20140526.Client(config);
                }
            }
        }
        return instance;
    }
}

Endpoint Configuration

Endpoint配置

Priority: explicit
endpoint
> region-based resolution via
regionId
.
java
// Preferred: explicit endpoint
config.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");

// Alternative: SDK resolves endpoint from region
config.setRegionId("cn-hangzhou");
优先级:显式指定
endpoint
> 基于
regionId
的自动解析。
java
// Preferred: explicit endpoint
config.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");

// Alternative: SDK resolves endpoint from region
config.setRegionId("cn-hangzhou");

VPC Endpoints

VPC终端节点

Use VPC endpoints when running inside Alibaba Cloud VPC (hybrid cloud, leased lines, multi-region):
java
config.setEndpoint("ecs-vpc.cn-hangzhou.aliyuncs.com");
当在阿里云VPC(混合云、专线、多区域)内运行时,使用VPC终端节点:
java
config.setEndpoint("ecs-vpc.cn-hangzhou.aliyuncs.com");

File Upload APIs (Advance)

文件上传API(进阶)

For file upload APIs (e.g., Visual Intelligence), set both
regionId
and
endpoint
to the same region. Otherwise you may see timeouts due to cross-region OSS access:
java
config.setRegionId("cn-shanghai");
config.setEndpoint("objectdet.cn-shanghai.aliyuncs.com");
// For VPC file upload authorization:
client._openPlatformEndpoint = "openplatform-vpc.cn-shanghai.aliyuncs.com";
对于文件上传API(如视觉智能API),需将regionId和endpoint设置为同一区域。否则可能因跨区域OSS访问导致超时:
java
config.setRegionId("cn-shanghai");
config.setEndpoint("objectdet.cn-shanghai.aliyuncs.com");
// For VPC file upload authorization:
client._openPlatformEndpoint = "openplatform-vpc.cn-shanghai.aliyuncs.com";

Synchronous vs Asynchronous

同步与异步客户端对比

ModeSDK ArtifactWhen to Use
Synchronous
com.aliyun:{productCode}{version}
Simple flows, low concurrency, easier debugging
Asynchronous
com.aliyun:alibabacloud-{productCode}{version}
High concurrency/throughput, non-blocking I/O
Async example:
java
AsyncClient client = AsyncClient.builder()
    .region("cn-hangzhou")
    .credentialsProvider(provider)
    .overrideConfiguration(ClientOverrideConfiguration.create()
        .setEndpointOverride("ecs.cn-chengdu.aliyuncs.com"))
    .build();

CompletableFuture<DescribeRegionsResponse> response = client.describeRegions(request);
response.thenAccept(resp -> System.out.println(new Gson().toJson(resp)))
    .exceptionally(throwable -> { System.out.println(throwable.getMessage()); return null; });
// Always close async client when done
client.close();
模式SDK制品使用场景
同步
com.aliyun:{productCode}{version}
流程简单、低并发场景,调试更便捷
异步
com.aliyun:alibabacloud-{productCode}{version}
高并发/高吞吐量场景,非阻塞I/O
异步示例:
java
AsyncClient client = AsyncClient.builder()
    .region("cn-hangzhou")
    .credentialsProvider(provider)
    .overrideConfiguration(ClientOverrideConfiguration.create()
        .setEndpointOverride("ecs.cn-chengdu.aliyuncs.com"))
    .build();

CompletableFuture<DescribeRegionsResponse> response = client.describeRegions(request);
response.thenAccept(resp -> System.out.println(new Gson().toJson(resp)))
    .exceptionally(throwable -> { System.out.println(throwable.getMessage()); return null; });
// Always close async client when done
client.close();