【问题标题】:Generic Aws client builder with Java SDK具有 Java SDK 的通用 Aws 客户端构建器
【发布时间】:2021-01-05 11:18:57
【问题描述】:

我正在处理一个项目,现在我们请求为所有实例(Ec2、S3 等...)提供使 coll 认为是代理服务器的选项。 例如,我有:

AmazonElasticLoadBalancing elbClient = AmazonElasticLoadBalancingClientBuilder.standard()       .withRegion(region.getName()).withCredentials(credentials).build();

AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard().withRegion(region).withCredentials(getCredentials()).build();

在我项目的很多地方。

检查 AWS Java SDK 文档后,我发现我需要在使用 build() 之前添加 withClientConfiguration(someMethodToGetProxyConfig())

我对 java 还是很陌生,我很难创建一个足够通用的函数来为所有这些类型的客户端执行此操作。 我试过了:

public static AwsClientBuilder clientBuilder(AwsClientBuilder client) throws ServiceWareException {
        final String PROXY = "proxy_host_port";
        String hasProxy = Configuration.getConfigurationParameter(PROXY);
        client = client.withRegion(getRegion()).withCredentials(getCredentials());
        if (!hasProxy.isEmpty() && hasProxy != null)
            client = client.withClientConfiguration(getProxyConfig());
        return (AwsClientBuilder) client.build();

    }

但它失败了,因为我无法将 AmazonEC2ClientBuilder 转换为 AwsClientBuilder。 有人可以分享一些关于如何做到这一点的提示,或者可能有做过类似事情的经验吗?

【问题讨论】:

    标签: java amazon-web-services aws-sdk


    【解决方案1】:

    在您的最后一行中,您调用了.build(),它返回一个客户端而不是客户端builder。如果您删除对.build() 的调用,那么我想代码会起作用。

    public static AwsClientBuilder clientBuilder(AwsClientBuilder client) throws ServiceWareException {
        final String PROXY = "proxy_host_port";
        String hasProxy = Configuration.getConfigurationParameter(PROXY);
        client = client.withRegion(getRegion()).withCredentials(getCredentials());
        if (!hasProxy.isEmpty() && hasProxy != null)
            client = client.withClientConfiguration(getProxyConfig());
        return client;
    }
    

    如果你想使用这个,你需要在结果上调用.build。为了使其能够很好地进行类型检查,您可能还希望将泛型类型参数添加到签名中(因此 .build 返回正确类型的值)。

    public static <S extends AwsClientBuilder<S, T>, T> AwsClientBuilder<S, T> clientBuilder(AwsClientBuilder<S, T> client) throws ServiceWareException {
        ...
    }
    

    如果你想让这个方法真正构建客户端,你可以在方法中调用.build,但是它需要返回一个客户端,而不是一个客户端构建器。由于这是一种不同的行为,因此我更改了方法的名称以反映这一点。

    public static <S extends AwsClientBuilder<S, T>, T> T buildClient(AwsClientBuilder<S, T> client) throws ServiceWareException {
        final String PROXY = "proxy_host_port";
        String hasProxy = Configuration.getConfigurationParameter(PROXY);
        client = client.withRegion(getRegion()).withCredentials(getCredentials());
        if (!hasProxy.isEmpty() && hasProxy != null)
            client = client.withClientConfiguration(getProxyConfig());
        return client.build();
    }
    

    【讨论】:

    • 我希望我能多投一个赞成票,非常感谢,这对我帮助很大,也帮助我更多地理解泛型 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多