public static void Excute(HttpJobItem item, string jobName = null, string queuename = null, bool isretry = false, PerformContext context = null)
        {
            var logList = new List <string>();

            try
            {
                if (context == null)
                {
                    return;
                }
                context.Items.TryGetValue("Data", out var runTimeDataItem);
                var runTimeData = runTimeDataItem as string;
                if (!string.IsNullOrEmpty(runTimeData))
                {
                    item.Data = runTimeData;
                }
                if (item.Timeout < 1)
                {
                    item.Timeout = 5000;
                }
                RunWithTry(() => context.SetTextColor(ConsoleTextColor.Yellow));
                RunWithTry(() => context.WriteLine($"{Strings.JobStart}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"));
                logList.Add($"{Strings.JobStart}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                RunWithTry(() => context.WriteLine($"{Strings.JobName}:{item.JobName ?? string.Empty}|{Strings.QueuenName}:{(string.IsNullOrEmpty(item.QueueName) ? "DEFAULT":item.QueueName)}"));
                logList.Add($"{Strings.JobName}:{item.JobName ?? string.Empty}|{Strings.QueuenName}:{(string.IsNullOrEmpty(item.QueueName) ? "DEFAULT" : item.QueueName)}");
                RunWithTry(() => context.WriteLine($"{Strings.JobParam}:【{JsonConvert.SerializeObject(item)}】"));
                logList.Add($"{Strings.JobParam}:【{JsonConvert.SerializeObject(item, Formatting.Indented)}】");
                HttpClient client;
                if (!string.IsNullOrEmpty(HangfireHttpJobOptions.Proxy))
                {
                    // per proxy per HttpClient
                    client = HangfireHttpClientFactory.Instance.GetProxiedHttpClient(HangfireHttpJobOptions.Proxy);
                    RunWithTry(() => context.WriteLine($"Proxy:{HangfireHttpJobOptions.Proxy}"));
                    logList.Add($"Proxy:{HangfireHttpJobOptions.Proxy}");
                }
                else
                {
                    //per host per HttpClient
                    client = HangfireHttpClientFactory.Instance.GetHttpClient(item.Url);
                }
                var         httpMesage   = PrepareHttpRequestMessage(item, context);
                var         cts          = new CancellationTokenSource(TimeSpan.FromMilliseconds(item.Timeout));
                var         httpResponse = client.SendAsync(httpMesage, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                HttpContent content      = httpResponse.Content;
                string      result       = content.ReadAsStringAsync().GetAwaiter().GetResult();
                RunWithTry(() => context.WriteLine($"{Strings.ResponseCode}:{httpResponse.StatusCode}"));
                logList.Add($"{Strings.ResponseCode}:{httpResponse.StatusCode}");

                //检查HttpResponse StatusCode
                if (HangfireHttpJobOptions.CheckHttpResponseStatusCode(httpResponse.StatusCode))
                {
                    RunWithTry(() => context.WriteLine($"{Strings.ResponseCode}:{httpResponse.StatusCode} ===> CheckResult: Ok "));
                    logList.Add($"{Strings.ResponseCode}:{httpResponse.StatusCode} ===> CheckResult: Ok ");
                }
                else
                {
                    throw new HttpStatusCodeException(httpResponse.StatusCode);
                }

                RunWithTry(() => context.WriteLine($"{Strings.JobResult}:{result}"));
                logList.Add($"{Strings.JobResult}:{result}");
                RunWithTry(() => context.WriteLine($"{Strings.JobEnd}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"));
                logList.Add($"{Strings.JobEnd}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                SendSuccessMail(item, string.Join("<br/>", logList));
            }
            catch (Exception ex)
            {
                RunWithTry(() => context.SetTextColor(ConsoleTextColor.Red));
                Logger.ErrorException("HttpJob.Excute=>" + item, ex);
                RunWithTry(() => context.WriteLine(ex.ToString()));
                if (!item.EnableRetry)
                {
                    SendFailMail(item, string.Join("<br/>", logList), ex);
                    AddErrToJob(context, ex);
                    return;
                }
                //获取重试次数
                var count = RunWithTry <string>(() => context.GetJobParameter <string>("RetryCount")) ?? string.Empty;
                if (count == "3")//重试达到三次的时候发邮件通知
                {
                    RunWithTry(() => context.WriteLine(Strings.LimitReached));
                    logList.Add(Strings.LimitReached);
                    SendFailMail(item, string.Join("<br/>", logList), ex);
                    AddErrToJob(context, ex);
                    return;
                }

                context.Items.Add("RetryCount", count);
                throw;
            }
        }
Exemple #2
0
        /// <summary>
        /// Run HttpRequest
        /// </summary>
        /// <param name="item"></param>
        /// <param name="context"></param>
        /// <param name="logList"></param>
        /// <param name="parentJob"></param>
        /// <exception cref="HttpStatusCodeException"></exception>
        private static bool Run(HttpJobItem item, PerformContext context, List <string> logList, HttpJobItem parentJob = null)
        {
            CancellationTokenSource cancelToken = null;

            try
            {
                if (parentJob != null)
                {
                    RunWithTry(() => context.SetTextColor(ConsoleTextColor.Green));
                    if (item.Timeout < 1)
                    {
                        item.Timeout = parentJob.Timeout;
                    }
                    if (item.Data.Contains("@parent@"))
                    {
                        item.Data = item.Data.Replace("@parent@", parentJob.Cron);
                    }
                    if (string.IsNullOrEmpty(item.BasicUserName))
                    {
                        item.BasicUserName = parentJob.BasicUserName;
                    }
                    if (string.IsNullOrEmpty(item.BasicPassword))
                    {
                        item.BasicPassword = parentJob.BasicPassword;
                    }
                    if (item.Headers == null || !item.Headers.Any())
                    {
                        item.Headers = parentJob.Headers;
                    }
                    if (string.IsNullOrEmpty(item.QueueName))
                    {
                        item.QueueName = parentJob.QueueName;
                    }
                    RunWithTry(() => context.WriteLine($"【{Strings.CallbackStart}】[{item.CallbackRoot}]"));
                    item.JobName = item.CallbackRoot;
                }
                else
                {
                    if (string.IsNullOrEmpty(item.CallbackRoot))
                    {
                        item.CallbackRoot = item.JobName;
                    }
                    if (item.Timeout < 1)
                    {
                        item.Timeout = 5000;
                    }
                    RunWithTry(() => context.SetTextColor(ConsoleTextColor.Yellow));
                }


                RunWithTry(() => context.WriteLine($"{Strings.JobStart}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"));
                logList.Add($"{Strings.JobStart}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                RunWithTry(() =>
                           context.WriteLine(
                               $"{Strings.JobName}:{item.JobName ?? string.Empty}|{Strings.QueuenName}:{(string.IsNullOrEmpty(item.QueueName) ? "DEFAULT" : item.QueueName)}"));
                logList.Add(
                    $"{Strings.JobName}:{item.JobName ?? string.Empty}|{Strings.QueuenName}:{(string.IsNullOrEmpty(item.QueueName) ? "DEFAULT" : item.QueueName)}");
                RunWithTry(() => context.WriteLine($"{Strings.JobParam}:【{JsonConvert.SerializeObject(item)}】"));
                logList.Add($"{Strings.JobParam}:【{JsonConvert.SerializeObject(item, Formatting.Indented)}】");
                HttpClient client;
                if (!string.IsNullOrEmpty(HangfireHttpJobOptions.Proxy))
                {
                    // per proxy per HttpClient
                    client = HangfireHttpClientFactory.Instance.GetProxiedHttpClient(HangfireHttpJobOptions.Proxy);
                    RunWithTry(() => context.WriteLine($"Proxy:{HangfireHttpJobOptions.Proxy}"));
                    logList.Add($"Proxy:{HangfireHttpJobOptions.Proxy}");
                }
                else
                {
                    //per host per HttpClient
                    client = HangfireHttpClientFactory.Instance.GetHttpClient(item.Url);
                }

                var httpMesage = PrepareHttpRequestMessage(item, context, parentJob);
                cancelToken = new CancellationTokenSource(TimeSpan.FromMilliseconds(item.Timeout));
                var httpResponse = client.SendAsync(httpMesage, cancelToken.Token).ConfigureAwait(false).GetAwaiter()
                                   .GetResult();
                HttpContent content = httpResponse.Content;
                string      result  = content.ReadAsStringAsync().GetAwaiter().GetResult();
                RunWithTry(() => context.WriteLine($"{Strings.ResponseCode}:{httpResponse.StatusCode}"));
                logList.Add($"{Strings.ResponseCode}:{httpResponse.StatusCode}");

                //检查HttpResponse StatusCode
                if (HangfireHttpJobOptions.CheckHttpResponseStatusCode(httpResponse.StatusCode, result))
                {
                    RunWithTry(() =>
                               context.WriteLine($"{Strings.ResponseCode}:{httpResponse.StatusCode} ===> CheckResult: Ok "));
                    logList.Add($"{Strings.ResponseCode}:{httpResponse.StatusCode} ===> CheckResult: Ok ");
                }
                else
                {
                    throw new HttpStatusCodeException(httpResponse.StatusCode, result);
                }

                //检查是否有设置EL表达式
                if (!string.IsNullOrEmpty(item.CallbackEL))
                {
                    var elResult = InvokeSpringElCondition(item.CallbackEL, result, context,
                                                           new Dictionary <string, object> {
                        { "resultBody", result }
                    });
                    if (!elResult)
                    {
                        throw new HttpStatusCodeException(item.CallbackEL, result);
                    }

                    RunWithTry(() => context.WriteLine($"【{Strings.CallbackELExcuteResult}:Ok 】" + item.CallbackEL));
                }

                RunWithTry(() => context.WriteLine($"{Strings.JobResult}:{result}"));
                logList.Add($"{Strings.JobResult}:{result}");
                RunWithTry(() => context.WriteLine($"{Strings.JobEnd}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"));
                logList.Add($"{Strings.JobEnd}:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                if (parentJob != null)
                {
                    RunWithTry(() => context.WriteLine($"【{Strings.CallbackSuccess}】[{item.CallbackRoot}]"));
                }

                //到这里查看是否有 子Job
                if (item.Success != null)
                {
                    item.Cron = result; //父job的执行结果
                    item.Success.CallbackRoot = item.CallbackRoot + ".Success";
                    return(Run(item.Success, context, logList, item));
                }

                return(true);
            }
            catch (Exception e)
            {
                RunWithTry(() => context.SetTextColor(ConsoleTextColor.Red));
                if (cancelToken != null && cancelToken.IsCancellationRequested)
                {
                    //说明是被我们自己设置的timeout超时了
                    RunWithTry(() => context.WriteLine("【HttpJob Timeout】:" + item.Timeout + "ms"));
                }

                if (parentJob == null)
                {
                    throw;
                }
                Logger.ErrorException("HttpJob.Excute=>" + item, e);
                RunWithTry(() => context.WriteLine($"【{Strings.CallbackFail}】[{item.CallbackRoot}]"));
                if (e is HttpStatusCodeException exception && exception.IsEl)
                {
                    RunWithTry(() => context.WriteLine($"【{Strings.CallbackELExcuteResult}:Fail 】" + exception.El));
                }