-
Notifications
You must be signed in to change notification settings - Fork 21
BuildClient
MiNG edited this page May 8, 2018
·
4 revisions
构建 ILogServiceClient
最少需要 服务入口、项目名和访问密钥。
public static ILogServiceClient BuildSimpleClient()
{
return LogServiceClientBuilders.HttpBuilder
// 服务入口<endpoint>及项目名<projectName>。
.Endpoint("<endpoint>", "<projectName>")
// 访问密钥信息。
.Credential("<accessKeyId>", "<accessKey>")
.Build();
}
如果需要访问其它用户的资源,可以使用STS 访问方式进行访问。 由于 STS 每隔一段时间需要重新刷新 访问密钥 和 STS Token,所以只能使用动态提供者的形式。
注意:此示例为简单起见,仅演示如何使用动态服务凭据,并不保证生产上的可靠性。 如需要在生产上使用请务必确保
credential
的 线程安全性、首次访问可用性 及 定时器释放问题。
using System;
using System.Timers;
using Aliyun.Api.LogService;
using Aliyun.Api.LogService.Infrastructure.Authentication;
public static class LogServiceClientFactory
{
private static Credential credential;
public static ILogServiceClient BuildClientUsingStsToken()
{
var client = LogServiceClientBuilders.HttpBuilder
// 服务入口<endpoint>及项目名<projectName>
.Endpoint("<endpoint>", "<projectName>")
// 动态服务凭据
// 请注意此处提供的是委托,而非变量,此委托会在**每次执行**时被调用,请务必注意性能问题!
.Credential(() => credential)
.Build();
// 创建定时任务刷新服务凭据。
this.timer = new Timer(TimeSpan.FromMinutes(10).TotalMilliseconds); // 每10分钟执行
this.timer.Elapsed += (sender, args) => credential = AssumeRoleOrThrow(); // 定时执行的任务
this.timer.Start();
return client;
}
}
当前版本构建 ILogServiceClient
支持如下设置,更多信息请参阅 HttpLogServiceClientBuilder 的文档。
public static ILogServiceClient BuildFullClient()
{
return LogServiceClientBuilders.HttpBuilder
// 服务入口<endpoint>及项目名<projectName>。
.Endpoint("<endpoint>", "<projectName>")
// 访问密钥信息。
.Credential("<accessKeyId>", "<accessKey>")
// 设置每次请求超时时间。
.RequestTimeout(1000)
// 设置是否使用代理,为false时将会绕过系统代理。
.UseProxy(true)
// 设置代理信息,(可选)支持需要身份验证的代理设置。
.Proxy("<proxyHost>", proxyUserName: "<username>", proxyPassword: "<password>")
.Build();
}
在单元测试的场景下,可能需要使用 mock 的 HttpClient
。
此时可直接创建 HttpLogServiceClient
的实例,并注入 HttpClient
实例 及 访问密钥信息提供者。
public static ILogServiceClient BuildCustomClient()
{
return new HttpLogServiceClient
(
// 支持自定义 `HttpClient` 实例。
new HttpClient(),
// 访问密钥信息提供者。
() => new Credential("<accessKeyId>", "<accessKey>")
);
}