您的应用建立的每个 HTTP 连接都会产生一定的开销。此库支持批处理,可让您的应用将多个 API 调用放入单个 HTTP 请求中。下面列举了一些您可能希望使用批处理的情况:
- 您发出许多小请求,并且希望尽可能减少 HTTP 请求开销。
- 用户在应用离线时对数据进行了更改,因此应用需要通过发送大量更新和删除来将其本地数据与服务器同步。
注意:每个批量请求最多只能调用 1000 个调用。 如果您需要进行更多调用,请使用多个批量请求。
注意:不能在批处理请求中使用媒体上传对象。
详细信息
如需创建批量请求,可以实例化 BatchRequest
对象,然后为要执行的每个请求调用 Queue
方法。对于每个请求,传入一个回调,以便在应用收到该请求的响应时调用它。
该回调函数的参数为:
- 内容
- 内容响应,如果请求失败,则返回
null
。 - 错误
- 错误,如果请求成功,则返回
null
。 - index
- 单个请求的索引。
- 私信
- 包含其所有标头和内容的完整 HTTP 消息。
ExecuteAsync
方法来发出请求。
在以下代码段中,系统会将两个 API 请求批量处理为一个 HTTP 请求,并为每个 API 请求提供一个回调:
UserCredential credential; using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { CalendarService.Scope.Calendar }, "user", CancellationToken.None, new FileDataStore("Calendar.Sample.Store")); } // Create the service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Calendar API Sample", }); // Create a batch request. var request = new BatchRequest(service); request.Queue<CalendarList>(service.CalendarList.List(), (content, error, i, message) => { // Put your callback code here. }); request.Queue<Event>(service.Events.Insert( new Event { Summary = "Learn how to execute a batch request", Start = new EventDateTime() { DateTime = new DateTime(2014, 1, 1, 10, 0, 0) }, End = new EventDateTime() { DateTime = new DateTime(2014, 1, 1, 12, 0, 0) } }, "YOUR_CALENDAR_ID_HERE"), (content, error, i, message) => { // Put your callback code here. }); // You can add more Queue calls here. // Execute the batch request, which includes the 2 requests above. await request.ExecuteAsync();