private Categoria ObterCategoriaResult(HttpClient httpClient, string categoria)
        {
            var response = _clientPolicySpotify.Execute(() =>
            {
                var urlCategoria = string.Format(_config.UrlCategoria, categoria);
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", TokenDeAcesso);
                return(httpClient.GetAsync(urlCategoria).Result);
            });

            var retornoCategoria = JsonConvert.DeserializeAnonymousType(
                response.Content.ReadAsStringAsync().Result,
                new
            {
                icons = new[]
                {
                    new
                    {
                        url = string.Empty
                    }
                },
                name = string.Empty
            }
                );

            return(new Categoria
            {
                DataDeCriacao = DateTime.Now,
                ImagemURL = retornoCategoria.icons.First().url,
                Nome = retornoCategoria.name,
                Status = (int)Enumeracao.ESituacao.Ativo
            });
        }
コード例 #2
0
        public void Subscribe <T>(EventHandlers.EventHandler <T> eventHandler) where T : Event
        {
            if (!connection.IsConnected)
            {
                connection.TryConnect();
            }

            var name = typeof(T).FullName;

            if (handlers.ContainsKey(name))
            {
                handlers[name].Add(eventHandler);
            }
            else
            {
                policy.Execute(() =>
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: name);
                        handlers.Add(name, new List <IEventHandler>());
                        handlers[name].Add(eventHandler);
                        eventTypes.Add(typeof(T));
                    }
                });
            }
        }
コード例 #3
0
        private IEnumerable <IRawTemplate> LoadTemplatesFromDirectory()
        {
            var directory = new DirectoryInfo(DefaultTemplateFolder);

            foreach (var file in directory.GetFiles(DefaultTemplateSearchPattern, SearchOption.AllDirectories)
                     .OrderBy(f => f.FullName))
            {
                if (ShouldIgnoreFile(file))
                {
                    _logger.LogDebug("{filePath} ignored using a {MockIgnoreFileName} file", Path.GetRelativePath(DefaultTemplateFolder, file.FullName), MockIgnoreFileName);
                    continue;
                }

                var name       = Path.GetRelativePath(directory.FullName, file.FullName);
                var rawContent = string.Empty;

                _retryPolicy.Execute(() =>
                {
                    using (var stream = File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
                        using (var streamReader = new StreamReader(stream))
                        {
                            rawContent = streamReader.ReadToEnd();
                        }
                });

                yield return(new RawTemplate(name, rawContent));
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: Al-Hurr/Insta_Like_Bot
        static async Task MainAsync()
        {
            var options = new ChromeOptions();

            // Установляем ведение журнала событий
            options.SetLoggingPreference(LogType.Browser, LogLevel.All);
            // Открываем браузер в режиме разработчика
            options.AddArguments("--auto-open-devtools-for-tabs");

            using (var driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), options, TimeSpan.FromMinutes(5)))
            {
                try
                {
                    // Программа будет выполнятся 7 мин
                    driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromMinutes(7);
                    // Открываем браузер в полноэкранном режиме
                    driver.Manage().Window.Maximize();
                    // Метод входа в аккаунт
                    await LogInAsync(driver);
                    await Delay(3);

                    // Нажимаем кнопку Instagram
                    _retryPolicy.Execute(() =>
                    {
                        ExecuteAsyncJS(driver, "if(document.querySelector('nav a')){document.querySelector('nav a').click();} arguments[arguments.length - 1]();");
                    });
                    // Если появится модалка, чтобы включить уведомления, говорим не включать
                    _retryPolicy.Execute(() =>
                    {
                        ExecuteAsyncJS(driver,
                                       "if(document.querySelector('button[class=\"aOOlW   HoLwm \"]')){document.querySelector('button[class=\"aOOlW   HoLwm \"]').click()} arguments[arguments.length - 1]();");
                    });

                    await Delay(3);

                    // Скрипт для нажатия кнопки "мне нрав"
                    ExecuteAsyncJS(driver, _containerLikeScript);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("Logs from browser:");
                    var logs = driver.Manage().Logs.GetLog(LogType.Browser).ToList();
                    foreach (var log in logs)
                    {
                        Console.WriteLine(log);
                    }
                    throw;
                }
                finally
                {
                    driver.Quit();
                }
            }
        }
コード例 #5
0
        public IEnumerable <EventData> Load(string partitionKey, int version)
        {
            var minRowKey = version.ToString("D10");
            var query     = GetEntitiesQuery(partitionKey, minRowKey, RowKeyVersionUpperLimit);

            // TODO: use async APIs, continuation tokens
            var all = eventStoreRetryPolicy.Execute(() => query.Result);

            return(all.Select(x => Mapper.Map(x, new EventData {
                Version = int.Parse(x.RowKey)
            })));
        }
コード例 #6
0
ファイル: RedisScheduler.cs プロジェクト: zmk523/DotnetSpider
 /// <summary>
 /// Check whether the request is duplicate.
 /// </summary>
 /// <param name="request">Request</param>
 /// <returns>Whether the request is duplicate.</returns>
 public virtual bool IsDuplicate(Request request)
 {
     return(_retryPolicy.Execute(() =>
     {
         bool isDuplicate = _redisConnection.Database.SetContains(_setKey, request.Identity);
         if (!isDuplicate)
         {
             _redisConnection.Database.SetAdd(_setKey, request.Identity);
         }
         return isDuplicate;
     }));
 }
コード例 #7
0
        public bool ConnectRbtMQ()
        {
            lock (this.lock_sync)
            {
                // 如果我们想指定处理多个异常类型通过OR即可
                //ConnectionFactory.CreateConnection期间无法打开连接时抛出异常
                RetryPolicy policy = RetryPolicy.Handle <SocketException>()
                                     .Or <BrokerUnreachableException>()
                                     .WaitAndRetry(5, retryAttempt =>
                                                   TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                });    // 重试次数,提供等待特定重试尝试的持续时间的函数,每次重试时调用的操作。
                policy.Execute(() =>
                {
                    _connection = _connectionFactory.CreateConnection();
                });

                if (IsConnected)
                {
                    //当连接被破坏时引发。如果在添加事件处理程序时连接已经被销毁,事件处理程序将立即被触发。
                    // _connection.ConnectionShutdown += this.OnConnectionShutdown;
                    //在连接调用的回调中发生异常时发出信号。当ConnectionShutdown处理程序抛出异常时,此事件将发出信号。如果将来有更多的事件出现在RabbitMQ.Client.IConnection上,那么这个事件当这些事件处理程序中的一个抛出异常时,它们将被标记。
                    //_connection.CallbackException += this.OnCallbackException;
                    //_connection.ConnectionBlocked += this.OnConnectionBlocked;

                    return(true);
                }
                else
                {
                    //MstCore.Pub.MstPub.Logs("FATAL ERROR: RabbitMQ connections could not be created and opened");
                    return(false);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// 发布事件
        /// </summary>
        /// <param name="event"></param>
        public void Publish(IntegrationEvent @event)
        {
            //1、保证连接是否有效
            if (!this._persistentConnection.IsConnected)
            {
                this._persistentConnection.TryConnect();
            }

            //2、声明事件发布重试策略(指数退避算法),处理瞬时或不确定移除导致失败的情况。
            RetryPolicy policy = RetryPolicy.Handle <BrokerUnreachableException>()
                                 .Or <SocketException>()
                                 .WaitAndRetry(this._retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                this._logger.LogWarning(ex.ToString());
            });

            //3、发布事件到消息队列
            using (IModel channel = _persistentConnection.CreateModel())        //创建信道
            {
                var eventName = @event.GetType().Name;                          //事件名称
                channel.ExchangeDeclare(exchange: BROKER_NAME, type: "direct"); //申明交换机

                //将事件对象序列化成(RabbitMQ能传递的)二进制块。
                var message = JsonConvert.SerializeObject(@event);
                var body    = Encoding.UTF8.GetBytes(message);
                //发布事件
                policy.Execute(() =>
                {
                    channel.BasicPublish(exchange: BROKER_NAME,
                                         routingKey: eventName,
                                         basicProperties: null,
                                         body: body);
                });
            }
        }
コード例 #9
0
 public bool TryConnect()
 {
     _logger?.LogInformation("正在连接RabbitMQ....");
     lock (_onlineRabbitMQLock)
     {
         RetryPolicy policy = Policy.Handle <SocketException>()
                              .Or <BrokerUnreachableException>()
                              .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
         {
             _logger?.LogWarning(ex, "RabbitMQ连接超时,TimeOut={TimeOut}, ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message);
         }
                                            );
         policy.Execute(() => _connection = _connectionFactory.CreateConnection());
         if (IsConnected)
         {
             _connection.ConnectionShutdown += OnConnectionShutdown;
             _connection.CallbackException  += OnCallbackException;
             _connection.ConnectionBlocked  += OnConnectionBlocked;
             _logger?.LogInformation("RabbitMQ已连接到{HostName}", _connection.Endpoint.HostName);
             return(true);
         }
         _logger?.LogCritical("致命错误:无法连接RabbitMQ");
         return(false);
     }
 }
コード例 #10
0
        public CloudBlobStorage(CloudStorageAccount account, string rootContainerName, ILogger <CloudBlobStorage> logger)
        {
            this.account           = account;
            this.rootContainerName = rootContainerName;
            this.logger            = logger;

            this.blobClient = account.CreateCloudBlobClient();
            var blobRequestOptions = new BlobRequestOptions
            {
                RetryPolicy = new Microsoft.WindowsAzure.Storage.RetryPolicies.NoRetry()
            };

            blobClient.DefaultRequestOptions = blobRequestOptions;

            //previous version
            //blobClient.RetryPolicy = new NoRetry();

            readRetryPolicy = Policy.Handle <Exception>().WaitAndRetry(new[] { TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1) },
                                                                       (ex, ts, countRetry, context) => logger.LogWarning("An error occurred in attempt number {1} to read from blob storage: {0}", ex.Message, countRetry)); /*Trace*/

            writeRetryPolicy = Policy.Handle <Exception>().WaitAndRetry(new[] { TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(10) },
                                                                        (ex, ts, countRetry, context) => logger.LogWarning("An error occurred in attempt number {1} to write to blob storage: {0}", ex.Message, countRetry)); /*Trace*/

            this.containerReference = blobClient.GetContainerReference(this.rootContainerName);
            writeRetryPolicy.Execute(() => containerReference.CreateIfNotExistsAsync());
        }
コード例 #11
0
        public async Task <IEnumerable <ProviderVacancySummary> > GetVacanciesAssociatedToProvider(long ukprn)
        {
            var builder = Builders <Vacancy> .Filter;
            var filter  =
                builder.Eq(ProviderUkprnFieldName, ukprn) &
                builder.Ne(IsDeletedFieldName, true);

            var collection = GetCollection <Vacancy>();

            var result = await RetryPolicy.Execute(_ =>
                                                   collection
                                                   .Find(filter)
                                                   .Project(x => new ProviderVacancySummary
            {
                Id = x.Id,
                VacancyOwner = x.OwnerType,
                VacancyReference = x.VacancyReference.GetValueOrDefault(),
                Status = x.Status,
                EmployerAccountId = x.EmployerAccountId
            })
                                                   .ToListAsync(),
                                                   new Context(nameof(GetVacanciesAssociatedToProvider)));

            return(result);
        }
コード例 #12
0
        public bool TryConnect()
        {
            lock (sync_root)
            {
                RetryPolicy policy = RetryPolicy.Handle <SocketException>()
                                     .Or <BrokerUnreachableException>()
                                     .WaitAndRetry(Configuration.FailReConnectRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    //_logger.LogWarning(ex.ToString());
                });

                policy.Execute(() =>
                {
                    _connection = _connectionFactory.CreateConnection(clientProvidedName: Configuration.ClientProvidedName);
                });

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;

                    return(true);
                }
                else
                {
                    //_logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");
                    return(false);
                }
            }
        }
コード例 #13
0
        public static IServiceProvider MigrateDbContext <TContext>(this IServiceProvider services, Action <TContext, IServiceProvider> seeder) where TContext : DbContext
        {
            var logger  = services.GetRequiredService <ILogger <TContext> >();
            var context = services.GetService <TContext>();

            try
            {
                logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}");

                _retryPolicy.Execute(() =>
                {
                    context.Database.Migrate();
                    seeder(context, services);
                });


                logger.LogInformation($"Migrated database associated with context {typeof(TContext).Name}");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"An error occurred while migrating the database used on context {typeof(TContext).Name}");
            }

            return(services);
        }
コード例 #14
0
 public async Task CreateAsync(EmployerProfile profile)
 {
     var collection = GetCollection <EmployerProfile>();
     await RetryPolicy.Execute(_ =>
                               collection.InsertOneAsync(profile),
                               new Context(nameof(CreateAsync)));
 }
コード例 #15
0
        public void Publish(IMessage message)
        {
            if (!_persistentConnection.IsConnected)
            {
                if (!CanConnect())
                {
                    return;
                }
            }

            RetryPolicy policy = Policy.Handle <BrokerUnreachableException>()
                                 .Or <SocketException>()
                                 .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                               (ex, time) => { _logger.LogWarning(ex.ToString()); });

            using (IModel channel = _persistentConnection.CreateModel())
            {
                channel.ExchangeDeclare(
                    BrokerName,
                    "direct");

                byte[] body = Encoding.UTF8.GetBytes(_messageSerialiser.Serialise(message));

                policy.Execute(() => { channel.BasicPublish(BrokerName, message.Type, null, body); });
            }
        }
コード例 #16
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            RetryPolicy retryPolicy = Policy
                                      .Handle <BrokerUnreachableException>()
                                      .WaitAndRetry(eventBusOptions.RetryCount !.Value, retryNumber => TimeSpan.FromSeconds(Math.Pow(2, retryNumber)), (exception, sleepDuration) => Console.WriteLine($"RabbitMQ connection retry, sleep duration: {sleepDuration}"));

            ConnectionFactory connectionFactory = new()
            {
                HostName = eventBusOptions.Connection,
                UserName = eventBusOptions.UserName,
                Password = eventBusOptions.Password,
                DispatchConsumersAsync = true
            };

            retryPolicy.Execute(() =>
            {
                connection = connectionFactory.CreateConnection();
            });

            channel = connection !.CreateModel();

            channel.ExchangeDeclare(exchange: eventBusOptions.BrokerName, type: ExchangeType.Direct);

            channel.QueueDeclare(queue: eventBusOptions.ClientName, durable: true, exclusive: false, autoDelete: false, arguments: null);

            channel.QueueBind(queue: eventBusOptions.ClientName, exchange: eventBusOptions.BrokerName, routingKey: nameof(UserCreatedIntegrationEvent));

            AsyncEventingBasicConsumer consumer = new(channel);

            consumer.Received += HandleIntegrationEvent;

            channel.BasicConsume(queue: eventBusOptions.ClientName, autoAck: false, consumer: consumer);

            return(Task.CompletedTask);
        }
コード例 #17
0
        public async Task SendWithDelayAsync(Message message, int delayMilliseconds = 0)
        {
            s_logger.LogDebug("Preparing  to send message on topic {Topic}", message.Header.Topic);

            EnsureTopicExists(message.Header.Topic);

            ITopicClient topicClient;

            try
            {
                RetryPolicy policy = Policy
                                     .Handle <Exception>()
                                     .Retry(TopicConnectionRetryCount, (exception, retryNumber) =>
                {
                    s_logger.LogError(exception, "Failed to connect to topic {Topic}, retrying...", message.Header.Topic);

                    Thread.Sleep(TimeSpan.FromMilliseconds(TopicConnectionSleepBetweenRetriesInMilliseconds));
                }
                                            );

                topicClient = policy.Execute(() => _topicClientProvider.Get(message.Header.Topic));
            }
            catch (Exception e)
            {
                s_logger.LogError(e, "Failed to connect to topic {Topic}, aborting.", message.Header.Topic);
                throw;
            }

            try
            {
                s_logger.LogDebug(
                    "Publishing message to topic {Topic} with a delay of {Delay} and body {Request} and id {Id}.",
                    message.Header.Topic, delayMilliseconds, message.Body.Value, message.Id);

                var azureServiceBusMessage = new Microsoft.Azure.ServiceBus.Message(message.Body.Bytes);
                azureServiceBusMessage.UserProperties.Add("MessageType", message.Header.MessageType.ToString());
                azureServiceBusMessage.UserProperties.Add("HandledCount", message.Header.HandledCount);
                if (delayMilliseconds == 0)
                {
                    await topicClient.SendAsync(azureServiceBusMessage);
                }
                else
                {
                    var dateTimeOffset = new DateTimeOffset(DateTime.UtcNow.AddMilliseconds(delayMilliseconds));
                    await topicClient.ScheduleMessageAsync(azureServiceBusMessage, dateTimeOffset);
                }

                s_logger.LogDebug(
                    "Published message to topic {Topic} with a delay of {Delay} and body {Request} and id {Id}", message.Header.Topic, delayMilliseconds, message.Body.Value, message.Id);
                ;
            }
            catch (Exception e)
            {
                s_logger.LogError(e, "Failed to publish message to topic {Topic} with id {Id}, message will not be retried.", message.Header.Topic, message.Id);
            }
            finally
            {
                await topicClient.CloseAsync();
            }
        }
コード例 #18
0
        public bool TryConnect()
        {
            lock (_syncRoot)
            {
                //https://github.com/App-vNext/Polly.Extensions.Http
                RetryPolicy policy = Policy.Handle <SocketException>()
                                     .Or <BrokerUnreachableException>()
                                     .WaitAndRetry(_options.RetryCount
                                                   , retryAttempt =>
                {
                    _logger.LogDebug("RabbitMQ Client is retrying to connect. Attempt {retryAttempt}", retryAttempt);
                    return(TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
                }
                                                   , (ex, time) => { _logger.LogWarning(ex.ToString()); });
                policy.Execute(() =>
                {
                    _logger.LogInformation("RabbitMQ Client is trying to connect {MessageQueueServer}", _connectionFactory.Uri);
                    _connection = _connectionFactory.CreateConnection();
                });

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;
                    _logger.LogInformation($"RabbitMQ persistent connection acquired a connection {_connection.Endpoint.HostName} and is subscribed to failure events");
                    return(true);
                }

                _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");
                return(false);
            }
        }
        private async Task <ReportStrategyResult> GetProviderApplicationsAsync(long ukprn, DateTime fromDate, DateTime toDate)
        {
            var collection = GetCollection <BsonDocument>();

            var queryJson = QueryFormat
                            .Replace(QueryUkprn, ukprn.ToString())
                            .Replace(QueryFromDate, fromDate.ToString("o"))
                            .Replace(QueryToDate, toDate.ToString("o"));

            var bson = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument[]>(queryJson);

            var results = await RetryPolicy.Execute(_ =>
                                                    collection.Aggregate <BsonDocument>(bson).ToListAsync(),
                                                    new Context(nameof(GetProviderApplicationsAsync)));

            await ProcessResultsAsync(results);

            _logger.LogInformation($"Report parameters ukprn:{ukprn} fromDate:{fromDate} toDate:{toDate} returned {results.Count} results");

            var dotNetFriendlyResults = results.Select(BsonTypeMapper.MapToDotNetValue);
            var data = JsonConvert.SerializeObject(dotNetFriendlyResults);

            var headers = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Date", _timeProvider.Now.ToUkTime().ToString("dd/MM/yyyy HH:mm:ss")),
                new KeyValuePair <string, string>("Total_Number_Of_Applications", results.Count.ToString())
            };

            return(new ReportStrategyResult(headers, data));
        }
コード例 #20
0
        public static IConnection Create(RabbitMQOptions options)
        {
            var theConnectionFactory = new ConnectionFactory {
                AutomaticRecoveryEnabled = true,
                HostName = options.Hostname,
                UserName = options.Username,
                Password = options.Password
            };

            RetryPolicy thePolicy = Policy
                                    .Handle <SocketException>()
                                    .Or <BrokerUnreachableException>()
                                    .WaitAndRetry(
                retryCount: ConnectionFactoryRetryCount,
                sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
                );

            IConnection?theConnection = null;

            thePolicy.Execute(() => theConnection = theConnectionFactory.CreateConnection());

            if (theConnection == null || !theConnection.IsOpen)
            {
                throw new InvalidOperationException("RabbitMQ connection could not be created.");
            }

            return(theConnection);
        }
コード例 #21
0
        public static IWebHost MigrateDbContext <TContext>(this IWebHost webHost) where TContext : DbContext
        {
            using (var scope = webHost.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var logger   = services.GetRequiredService <ILogger <TContext> >();
                var context  = services.GetService <TContext>();

                try
                {
                    logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}");

                    RetryPolicy retry = Policy.Handle <SqlException>()
                                        .WaitAndRetry(new TimeSpan[]
                    {
                        TimeSpan.FromSeconds(5),
                        TimeSpan.FromSeconds(10),
                        TimeSpan.FromSeconds(15),
                    });

                    retry.Execute(() =>
                    {
                        context.Database.Migrate();
                    });

                    logger.LogInformation($"Migrated database associated with context {typeof(TContext).Name}");
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $"An error occurred while migrating the database used on context {typeof(TContext).Name}");
                }
            }

            return(webHost);
        }
コード例 #22
0
        public void Publish(IntegrationEvent @event)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }
            RetryPolicy policy = Policy.Handle <BrokerUnreachableException>().Or <SocketException>()
                                 .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                _logger?.LogError(ex, "发布事件失败: EventId={EventId} Timeout={Timeout} ({ExceptionMessage})", @event.ID, $"{time.TotalSeconds:n1}", ex.Message);
            });
            string eventName = @event.GetType().Name;

            _logger?.LogTrace("创建RabbitMQ发布事件通道: {EventId} ({EventName})", @event.ID, eventName);
            IModel channel = _persistentConnection.CreateModel();

            channel.ExchangeDeclare(_exchangeName, "direct");
            string message = JsonConvert.SerializeObject(@event);

            byte[] body = Encoding.UTF8.GetBytes(message);
            policy.Execute(() =>
            {
                IBasicProperties properties = channel.CreateBasicProperties();
                properties.DeliveryMode     = 2;
                _logger?.LogTrace("发布事件: {EventId}", @event.ID);
                channel.BasicPublish(_exchangeName, eventName, properties, body);
                channel.Dispose();
            });
        }
コード例 #23
0
        public static string DownloadImage(string downloadUrl, string useFileName = null)
        {
            var fileName = useFileName ?? GetSHA1HashString(downloadUrl);

            var imageCachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Octopus\\Temp\\Samples\\ImageCache");

            if (!Directory.Exists(imageCachePath))
            {
                Directory.CreateDirectory(imageCachePath);
            }
            var imageFilePath = Path.Combine(imageCachePath, fileName);

            if (File.Exists(imageFilePath))
            {
                Log.Debug("Found {URL} cached as {FileName}!", downloadUrl, imageFilePath);
            }
            else
            {
                Log.Information("Downloading {URL} and saving as {FileName}...", downloadUrl, imageFilePath);
                using (var client = new WebClient())
                {
                    Retry.Execute(() =>
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        client.DownloadFile(downloadUrl, imageFilePath);
                    });
                }
            }

            return(imageFilePath);
        }
コード例 #24
0
ファイル: JsonHttpClient.cs プロジェクト: timmyreilly/draco
        public async Task <HttpResponse <TResponse> > GetAsync <TResponse>(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }

            if (Uri.TryCreate(url, UriKind.Absolute, out _) == false)
            {
                throw new ArgumentException($"[{url}] is not a valid absolute URL.", nameof(url));
            }

            var httpResponse = await httpRetryPolicy.Execute(async() => EnsureSuccessStatusCode(await httpClient.GetAsync(url)));

            return(new HttpResponse <TResponse>(httpResponse.StatusCode, await TryToGetResponseData <TResponse>(httpResponse)));
        }
コード例 #25
0
        /// <param name="event"></param>
        public void Publish(IntegrationEvent @event)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            RetryPolicy policy = Policy.Handle <BrokerUnreachableException>()
                                 .Or <SocketException>()
                                 .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                               (ex, time) =>
            {
                _logger.LogWarning(ex.ToString());
            }
                                               );

            using (IModel channel = _persistentConnection.CreateModel())
            {
                string eventName = @event.GetType().Name;
                channel.ExchangeDeclare(exchange: _brokerName, type: "direct");

                string message = JsonConvert.SerializeObject(@event);
                byte[] body    = Encoding.UTF8.GetBytes(message);

                policy.Execute(() =>
                {
                    IBasicProperties properties = channel.CreateBasicProperties();
                    properties.DeliveryMode     = 2;                 // persistent

                    channel.BasicPublish(exchange: _brokerName, routingKey: eventName, mandatory: true, basicProperties: properties, body: body);
                });
            }
        }
コード例 #26
0
        private void CheckPaymentTransaction(TPrimary doc)
        {
            if (!IsFeatureSupported(SelectedProcessingCenter, CCProcessingFeature.TransactionGetter))
            {
                return;
            }
            ICCPayment pDoc = GetPaymentDoc(doc);
            IEnumerable <V2.TransactionData> trans = null;

            if (LockExists(doc))
            {
                retryUnsettledTran.HandleError(i => GetTransByDoc(pDoc, i).Count > 0 ? true : false);
                try
                {
                    trans = retryUnsettledTran.Execute(() => GetPaymentProcessing().GetUnsettledTransactions(SelectedProcessingCenter));
                }
                catch (InvalidOperationException)
                { }
            }

            if (trans != null)
            {
                IEnumerable <string> result = PrepeareTransactionIds(GetTransByDoc(pDoc, trans));
                SyncPaymentTransactionById(doc, result);
            }
            ClearTransactionСaches();

            IExternalTransaction tran = ExternalTranHelper.GetActiveTransaction(GetExtTrans());

            if (tran != null)
            {
                TranStatusChanged(pDoc, tran.TransactionID);
            }
        }
コード例 #27
0
        public bool TryConnect()
        {
            lock (this.sync_root)
            {
                RetryPolicy policy = RetryPolicy.Handle <SocketException>() //如果我们想指定处理多个异常类型通过OR即可
                                     .Or <BrokerUnreachableException>()     //ConnectionFactory.CreateConnection期间无法打开连接时抛出异常
                                     .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                });    // 重试次数,提供等待特定重试尝试的持续时间的函数,每次重试时调用的操作。
                policy.Execute(() =>
                {
                    try
                    {
                        this._connection = _connectionFactory.CreateConnection();
                    }
                    catch { }
                });

                if (this.IsConnected)
                {
                    //当连接被破坏时引发。如果在添加事件处理程序时连接已经被销毁对于此事件,事件处理程序将立即被触发。
                    this._connection.ConnectionShutdown += this.OnConnectionShutdown;
                    //在连接调用的回调中发生异常时发出信号。当ConnectionShutdown处理程序抛出异常时,此事件将发出信号。如果将来有更多的事件出现在RabbitMQ.Client.IConnection上,那么这个事件当这些事件处理程序中的一个抛出异常时,它们将被标记。
                    this._connection.CallbackException += this.OnCallbackException;
                    this._connection.ConnectionBlocked += this.OnConnectionBlocked;
                    //LogHelperNLog.Info($"RabbitMQ persistent connection acquired a connection {_connection.Endpoint.HostName} and is subscribed to failure events");
                    return(true);
                }
                else
                {
                    // LogHelperNLog.Info("FATAL ERROR: RabbitMQ connections could not be created and opened");
                    return(false);
                }
            }
        }
コード例 #28
0
        private IServiceBusSenderWrapper GetSender(string topic)
        {
            EnsureTopicExists(topic);

            try
            {
                RetryPolicy policy = Policy
                                     .Handle <Exception>()
                                     .Retry(TopicConnectionRetryCount, (exception, retryNumber) =>
                {
                    s_logger.LogError(exception, "Failed to connect to topic {Topic}, retrying...",
                                      topic);

                    Thread.Sleep(TimeSpan.FromMilliseconds(TopicConnectionSleepBetweenRetriesInMilliseconds));
                }
                                            );

                return(policy.Execute(() => _serviceBusSenderProvider.Get(topic)));
            }
            catch (Exception e)
            {
                s_logger.LogError(e, "Failed to connect to topic {Topic}, aborting.", topic);
                throw;
            }
        }
コード例 #29
0
        public bool TryConnect()
        {
            _logger.Information("RabbitMQ Client is trying to connect");
            lock (sync_root)
            {
                RetryPolicy policy = RetryPolicy.Handle <SocketException>()
                                     .Or <BrokerUnreachableException>()
                                     .WaitAndRetry(Configuration.FailReConnectRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    _logger.LogWarning(ex.ToString());
                }
                                                   );

                policy.Execute(() =>
                {
                    _connection = _connectionFactory.CreateConnection(clientProvidedName: Configuration.ClientProvidedName);
                });

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;
                    _logger.Information($"RabbitMQ persistent connection acquired a connection {_connection.Endpoint.HostName} and is subscribed to failure events");

                    return(true);
                }
                else
                {
                    _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");
                    return(false);
                }
            }
        }
コード例 #30
0
ファイル: Test.cs プロジェクト: peishuli/nsb
        public void IntegrationTest()
        {
            using (var client = new HttpClient())
            {
                // Use Polly retry policy to handle http request, in the example below, we simply
                // retry three times (the interval will be determined by the timeout of the API)
                RetryPolicy retry = Policy
                                    .Handle <HttpRequestException>()
                                    .Retry(3);

                // Calling the api and capture the tracking id (i.e., a "transaction id")
                var transactionId = retry.Execute(() => CallApi(client));

                Console.WriteLine($"TransactionId = {transactionId}");

                // Wait for 5 seconds -- give Platform handler time to complete processing
                Thread.Sleep(TimeSpan.FromSeconds(20));

                // Get all log messages from elasitcsearch for a given transaction id
                var json = GetLogsFromElasticsearch(client, transactionId);
                // Verfiy that the total hit is >= 4
                dynamic result    = JsonConvert.DeserializeObject <dynamic>(json);
                int     totalHits = result.hits.total;
                Assert.True(totalHits >= 4);
            }
        }