コード例 #1
0
        public async Task <HttpResponseMessage> GetToApi(string apiUrl)
        {
            var _httpClient = new HttpClient();

            HttpResponseMessage response =
                await _httpRetryPolicy.ExecuteAsync(() =>
                                                    _timeoutPolicy.ExecuteAsync(
                                                        async token => await _httpClient.GetAsync($"{_baseUri}{apiUrl}", token), CancellationToken.None));

            return(response);

            #region Comentado

            /*
             * var client = new HttpClient();
             * var byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
             *
             * var content = new ByteArrayContent(byteData);
             *
             * content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
             *
             * var retryPolicy = _policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>(PolicyNames.BasicRetry)
             *                ?? Policy.NoOpAsync<HttpResponseMessage>();
             *
             * var context = new Context($"GetSomeData-{Guid.NewGuid()}", new Dictionary<string, object>
             *  {
             *      { PolicyContextItems.Logger, _logger }, { "url", apiUrl }
             *  });
             *
             * var retries = 0;
             *
             * var response = await retryPolicy.ExecuteAsync((ctx) =>
             * {
             *  client.DefaultRequestHeaders.Remove("retries");
             *  client.DefaultRequestHeaders.Add("retries", new[] { retries++.ToString() });
             *
             *  var baseUrl = _baseUri;
             *  //if (string.IsNullOrWhiteSpace(baseUrl))
             *  //{
             *  //    var uri = Request.GetUri();
             *  //    baseUrl = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
             *  //}
             *
             *  var isValid = Uri.IsWellFormedUriString(baseUrl + apiUrl, UriKind.Absolute);
             *
             *  return client.GetAsync(isValid ? $"{baseUrl}{apiUrl}" : $"{baseUrl}");
             * }, context);
             *
             * content.Dispose();
             *
             * return response;
             */
            #endregion
        }
コード例 #2
0
 public void Handle(FileEntity entity)
 {
     _timeoutPolicy.ExecuteAsync(
         async ct =>
     {
         try
         {
             await _ftpClient.UploadAsync(
                 entity.FullPath,
                 entity.FileName.GetFileName(!_options.DisableFileNameAddedTimeStamp));
         }
         catch (WebException we) when(we.Status == WebExceptionStatus.ConnectFailure)
         {
             _logger.LogError("注意:当前FTP 服务器连接不可用,为了保证传图顺利,请立即联系技术人员。");
         }
         catch (WebException we2)
         {
             _logger.LogError(we2, "其他Ftp错误。");
         }
     },
         CancellationToken.None)
     .GetAwaiter()
     .GetResult();
 }
コード例 #3
0
        public async Task <IActionResult> Get(int id)
        {
            var    httpClient      = _httpClientFactory.CreateClient("InventoryClient");
            string requestEndpoint = $"timeout/inventory/{id}";

            HttpResponseMessage response =
                await
                _httpRequestFallbackPolicy.ExecuteAsync(() =>
                                                        _httpRetryPolicy.ExecuteAsync(() =>
                                                                                      _timeoutPolicy.ExecuteAsync(
                                                                                          async token => await httpClient.GetAsync(requestEndpoint, token), CancellationToken.None)));

            if (response.IsSuccessStatusCode)
            {
                int itemsInStock = JsonConvert.DeserializeObject <int>(await response.Content.ReadAsStringAsync());
                return(Ok(itemsInStock));
            }

            if (response.Content != null)
            {
                return(StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync()));
            }
            return(StatusCode((int)response.StatusCode));
        }
コード例 #4
0
        private async Task <BigInteger> IndexBlocksAsync(string indexerId, BigInteger currentBlockNumber,
                                                         Func <BigInteger, bool> checkDelegate)
        {
            try
            {
                if (_firstRun && _indexingSettings.From == currentBlockNumber)
                {
                    await _logger.WriteInfoAsync
                    (
                        "BlockIndexingJob",
                        "IndexBlocksAsync",
                        indexerId,
                        $"Indexing begins from block-{currentBlockNumber}",
                        DateTime.UtcNow
                    );

                    var blockContent = await _rpcBlockReader.ReadBlockAsync(currentBlockNumber);

                    var blockContext = new BlockContext(Id, Version, indexerId, blockContent);

                    await _indexingService.IndexBlockAsync(blockContext);

                    currentBlockNumber++;

                    _firstRun = false;
                }

                var iterationVector = 0;

                while (checkDelegate(currentBlockNumber))
                {
                    BlockContent blockContent = null;

                    var transactionCount = 0;

                    await _logger.WriteInfoAsync
                    (
                        "BlockIndexingJob",
                        "IndexBlocksAsync",
                        indexerId,
                        $"Indexing block-{currentBlockNumber}, Vector:{iterationVector}",
                        DateTime.UtcNow
                    );

                    //Would throw on time out
                    await RetryPolicy.ExecuteAsync(async() =>
                    {
                        await _logger.WriteInfoAsync
                        (
                            "BlockIndexingJob",
                            "IndexBlocksAsync",
                            indexerId,
                            $"Block-{currentBlockNumber}, Vector:{iterationVector} Reading info",
                            DateTime.UtcNow
                        );

                        //Throws Timeout Exception
                        await TimeoutPolicy.ExecuteAsync(async() =>
                        {
                            blockContent = blockContent ?? await _rpcBlockReader.ReadBlockAsync(currentBlockNumber);
                        }, TimeSpan.FromMinutes(7));

                        await _logger.WriteInfoAsync
                        (
                            "BlockIndexingJob",
                            "IndexBlocksAsync",
                            indexerId,
                            $"Checking existence of the parent-{currentBlockNumber}",
                            DateTime.UtcNow
                        );

                        var blockContext = new BlockContext(Id, Version, indexerId, blockContent);
                        var blockExists  = await _blockService.DoesBlockExist(blockContent.BlockModel.ParentHash);

                        transactionCount = blockContent.Transactions.Count;
                        iterationVector  = blockExists ? 1 : -1; //That is how we deal with forks

                        await _logger.WriteInfoAsync
                        (
                            "BlockIndexingJob",
                            "IndexBlocksAsync",
                            indexerId,
                            $"Indexing block in DB -{currentBlockNumber}",
                            DateTime.UtcNow
                        );

                        // Throws Timeout Exception
                        await TimeoutPolicy.ExecuteAsync(async() =>
                        {
                            await _indexingService.IndexBlockAsync(blockContext);
                        }, TimeSpan.FromMinutes(5));
                    }, 5, 100);

                    await _logger.WriteInfoAsync
                    (
                        "BlockIndexingJob",
                        "IndexBlocksAsync",
                        indexerId,
                        $"Indexing completed for block-{currentBlockNumber}, Vector:{iterationVector}, transaction count - {transactionCount}",
                        DateTime.UtcNow
                    );

                    currentBlockNumber += iterationVector;
                }
            }
            catch (Exception e)
            {
                if (e is BlockIsNotYetMinedException)
                {
                    throw;
                }

                await _logger.WriteErrorAsync
                (
                    "BlockIndexingJob",
                    "RunAsync",
                    $"Indexing failed for block-{currentBlockNumber}",
                    e,
                    DateTime.UtcNow
                );

                throw;
            }

            return(currentBlockNumber);
        }