Quartz.Net分散式運用

来源:https://www.cnblogs.com/dasajia2lang/archive/2018/09/07/9605268.html
-Advertisement-
Play Games

Quartz.Net的集群部署詳解 標簽(空格分隔): Quartz.Net Job 最近工作上要用Job,公司的job有些不滿足個人的使用,於是就想自己搞一個Job站練練手,網上看了一下,發現Quartz,於是就瞭解了一下。 第一版 目前個人使用的是Asp.net Core,在core2.0下麵進 ...


Quartz.Net的集群部署詳解

標簽(空格分隔): Quartz.Net Job


最近工作上要用Job,公司的job有些不滿足個人的使用,於是就想自己搞一個Job站練練手,網上看了一下,發現Quartz,於是就瞭解了一下。

第一版

目前個人使用的是Asp.net Core,在core2.0下麵進行的開發。
第一版自己簡單的寫了一個調度器。

public static class SchedulerManage
{
        private static IScheduler _scheduler = null;

        private static object obj = new object();

        public static IScheduler Scheduler
        {
            get
            {
                var scheduler = _scheduler;
                if (scheduler == null)
                {
                    //在這之前有可能_scheduler被改變了scheduler用的還是原來的值
                    lock (obj)
                    {
                        //這裡讀取最新的記憶體裡面的值賦值給scheduler,保證讀取到的是最新的_scheduler
                        scheduler = Volatile.Read(ref _scheduler);
                        if (scheduler == null)
                        {
                            scheduler = GetScheduler().Result;
                            Volatile.Write(ref _scheduler, scheduler);
                        }
                    }
                }
                return scheduler;
            }
        }

        public static async Task<BaseResponse> RunJob(IJobDetail job, ITrigger trigger)
        {
            var response = new BaseResponse();
            try
            {
                var isExist = await Scheduler.CheckExists(job.Key);
                var time = DateTimeOffset.Now;
                if (isExist)
                {
                    //恢復已經存在任務
                    await Scheduler.ResumeJob(job.Key);
                }
                else
                {
                    time = await Scheduler.ScheduleJob(job, trigger);
                }
                response.IsSuccess = true;
                response.Msg = time.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {
                response.Msg = ex.Message;
            }
            return response;

        }


        public static async Task<BaseResponse> StopJob(JobKey jobKey)
        {
            var response = new BaseResponse();
            try
            {
                var isExist = await Scheduler.CheckExists(jobKey);
                if (isExist)
                {
                    await Scheduler.PauseJob(jobKey);
                }
                response.IsSuccess = true;
                response.Msg = "暫停成功!!";
            }
            catch (Exception ex)
            {
                response.Msg = ex.Message;
            }
            return response;
        }

        public static async Task<BaseResponse> DelJob(JobKey jobKey)
        {
            var response = new BaseResponse();
            try
            {
                var isExist = await Scheduler.CheckExists(jobKey);
                if (isExist)
                {
                    response.IsSuccess = await Scheduler.DeleteJob(jobKey);
                }
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Msg = ex.Message;
            }
            return response;
        }

        private static async Task<IScheduler> GetScheduler()
        {
            NameValueCollection props = new NameValueCollection() {
                {"quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);
            var scheduler = await factory.GetScheduler();
            await scheduler.Start();
            return scheduler;
        }
}

簡單的實現了,動態的運行job,暫停Job,添加job。弄完以後,發現貌似沒啥問題,只要自己把運行的job信息找張表存儲一下,好像都ok了。

輪到發佈的時候,突然發現現實機器不止一臺,是通過Nigix進行反向代理。突然發現以下幾個問題:

1,多台機器很有可能一個Job在多台機器上運行。
2,當進行部署的時候,必須得停掉機器,如何在機器停掉以後重新部署的時候自動恢復正在運行的Job。
3,如何均衡的運行所有job。

個人當時的想法

1,第一個問題:由於是經過Nigix的反向代理,添加Job和運行job只能落到一臺伺服器上,基本沒啥問題。個人控制好RunJob的介面,運行了一次,把JobDetail的那張表的運行狀態改成已運行,也就不存在多個機器同時運行的情況。
2,在第一個問題解決的情況下,由於我們公司的Nigix反向代理的邏輯是:均衡策略。所以均衡運行所有job都沒啥問題。
3,重點來了!!!!
如何在部署的時候恢復正在運行的Job?

由於我們已經有了一張JobDetail表。裡面可以獲取到哪些正在運行的Job。wome我們把他找出來直接在程式啟動的時候運行一下不就好了嗎嘛。

下麵是個人實現的:

//HostedService,在主機運行的時候運行的一個服務
public class HostedService : IHostedService
{

        public HostedService(ISchedulerJob schedulerCenter)
        {
            _schedulerJob = schedulerCenter;
        }

        private ISchedulerJob _schedulerJob = null;

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            LogHelper.WriteLog("開啟Hosted+Env:"+env);
            var reids= new RedisOperation();
            if (reids.SetNx("RedisJobLock", "1"))
            {               
                await _schedulerJob.StartAllRuningJob();
            }
            reids.Expire("RedisJobLock", 300);
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            LogHelper.WriteLog("結束Hosted");
            var redis = new RedisOperation();
            if (redis.RedisExists("RedisJobLock"))
            {
                var count=redis.DelKey("RedisJobLock");
                LogHelper.WriteLog("刪除Reidskey-RedisJobLock結果:" + count);
            }
        }
}

    //註入用的特性
    [ServiceDescriptor(typeof(ISchedulerJob), ServiceLifetime.Transient)]
    public class SchedulerCenter : ISchedulerJob
    {
        public SchedulerCenter(ISchedulerJobFacade schedulerJobFacade)
        {
            _schedulerJobFacade = schedulerJobFacade;
        }

        private ISchedulerJobFacade _schedulerJobFacade = null;

        public async Task<BaseResponse> DelJob(SchedulerJobModel jobModel)
        {
            var response = new BaseResponse();
            if (jobModel != null && jobModel.JobId != 0 && jobModel.JobName != null)
            {
                response = await _schedulerJobFacade.Modify(new SchedulerJobModifyRequest() { JobId = jobModel.JobId, DataFlag = 0 });
                if (response.IsSuccess)
                {
                    response = await SchedulerManage.DelJob(GetJobKey(jobModel));
                    if (!response.IsSuccess)
                    {
                        response = await _schedulerJobFacade.Modify(new SchedulerJobModifyRequest() { JobId = jobModel.JobId, DataFlag = 1 });
                    }
                }
            }
            else
            {
                response.Msg = "請求參數有誤";
            }
            return response;
        }

        public async Task<BaseResponse> RunJob(SchedulerJobModel jobModel)
        {
            if (jobModel != null)
            {
                var jobKey = GetJobKey(jobModel);

                var triggleBuilder = TriggerBuilder.Create().WithIdentity(jobModel.JobName + "Trigger", jobModel.JobGroup).WithCronSchedule(jobModel.JobCron).StartAt(jobModel.JobStartTime);
                if (jobModel.JobEndTime != null && jobModel.JobEndTime != new DateTime(1900, 1, 1) && jobModel.JobEndTime == new DateTime(1, 1, 1))
                {
                    triggleBuilder.EndAt(jobModel.JobEndTime);
                }
                triggleBuilder.ForJob(jobKey);
                var triggle = triggleBuilder.Build();
                var data = new JobDataMap();
                data.Add("***", "***");
                data.Add("***", "***");
                data.Add("***", "***");
                var job = JobBuilder.Create<SchedulerJob>().WithIdentity(jobKey).SetJobData(data).Build();
                var result = await SchedulerManage.RunJob(job, triggle);
                if (result.IsSuccess)
                {
                    var response = await _schedulerJobFacade.Modify(new SchedulerJobModifyRequest() { JobId = jobModel.JobId, JobState = 1 });
                    if (!response.IsSuccess)
                    {
                        await SchedulerManage.StopJob(jobKey);
                    }
                    return response;
                }
                else
                {
                    return result;
                }
            }
            else
            {
                return new BaseResponse() { Msg = "Job名稱為空!!" };
            }

        }

        public async Task<BaseResponse> StopJob(SchedulerJobModel jobModel)
        {
            var response = new BaseResponse();
            if (jobModel != null && jobModel.JobId != 0 && jobModel.JobName != null)
            {
                response = await _schedulerJobFacade.Modify(new SchedulerJobModifyRequest() { JobId = jobModel.JobId, JobState = 2 });
                if (response.IsSuccess)
                {
                    response = await SchedulerManage.StopJob(GetJobKey(jobModel));
                    if (!response.IsSuccess)
                    {
                        response = await _schedulerJobFacade.Modify(new SchedulerJobModifyRequest() { JobId = jobModel.JobId, JobState = 2 });
                    }
                }
            }
            else
            {
                response.Msg = "請求參數有誤";
            }
            return response;
        }

        private JobKey GetJobKey(SchedulerJobModel jobModel)
        {
            return new JobKey($"{jobModel.JobId}_{jobModel.JobName}", jobModel.JobGroup);
        }

        public async Task<BaseResponse> StartAllRuningJob()
        {
            try
            {
                var jobListResponse = await _schedulerJobFacade.QueryList(new SchedulerJobListRequest() { DataFlag = 1, JobState = 1, Environment=Kernel.Environment.ToLower() });
                if (!jobListResponse.IsSuccess)
                {
                    return jobListResponse;
                }
                var jobList = jobListResponse.Models;
                foreach (var job in jobList)
                {
                    await RunJob(job);
                }

                return new BaseResponse() { IsSuccess = true, Msg = "程式啟動時,啟動所有運行中的job成功!!" };
            }
            catch (Exception ex)
            {
                LogHelper.WriteExceptionLog(ex);
                return new BaseResponse() { IsSuccess = false, Msg = "程式啟動時,啟動所有運行中的job失敗!!" };
            }
        }
    }

在程式啟動的時候,把所有的Job去運行一遍,當中對於多次運行的用到了Redis的分散式鎖,現在啟動的時候鎖住,不讓別人運行,在程式卸載的時候去把鎖釋放掉!!感覺沒啥問題,主要是可能負載均衡有問題,全打到一臺伺服器上去了,勉強能夠快速的打到效果。當然高可用什麼的就先犧牲掉了。

坑點又來了

大家知道,在稍微大點的公司,運維和開發是分開的,公司用的daoker進行部署,在程式停止的時候,不會調用
HostedService的StopAsync方法!!
當時心裡真是一萬個和諧和諧奔騰而過!!
個人也就懶得和運維去扯這些東西了。最後的最後就是:設置一個redis的分散式鎖的過期時間,大概預估一個部署的時間,只要在部署直接,鎖能夠在就行了,然後每次部署的間隔要大於鎖過期時間。好麻煩,說多了都是淚!!

Quartz.Net的分散式集群運用

Schedule配置

        public async Task<IScheduler> GetScheduler()
        {
            var properties = new NameValueCollection();

            properties["quartz.serializer.type"] = "binary";

            //存儲類型
            properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            //表明首碼
            properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
            //驅動類型
            properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";                
            //資料庫名稱
            properties["quartz.jobStore.dataSource"] = "SchedulJob";
            //連接字元串Data Source = myServerAddress;Initial Catalog = myDataBase;User Id = myUsername;Password = myPassword;
            properties["quartz.dataSource.SchedulJob.connectionString"] = "Data Source =.; Initial Catalog = SchedulJob;User ID = sa; Password = *****;";
            //sqlserver版本(Core下麵已經沒有什麼20,21版本了)
            properties["quartz.dataSource.SchedulJob.provider"] = "SqlServer";
            //是否集群,集群模式下要設置為true
            properties["quartz.jobStore.clustered"] = "true";
            properties["quartz.scheduler.instanceName"] = "TestScheduler";
            //集群模式下設置為auto,自動獲取實例的Id,集群下一定要id不一樣,不然不會自動恢復
            properties["quartz.scheduler.instanceId"] = "AUTO";
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "25";
            properties["quartz.threadPool.threadPriority"] = "Normal";
            properties["quartz.jobStore.misfireThreshold"] = "60000";
            properties["quartz.jobStore.useProperties"] = "false";
            ISchedulerFactory factory = new StdSchedulerFactory(properties);
            return await factory.GetScheduler();
        }

然後是測試代碼:

        public async Task TestJob()
        {
            var sched = await GetScheduler();
            //Console.WriteLine("***** Deleting existing jobs/triggers *****");
            //sched.Clear();


            Console.WriteLine("------- Initialization Complete -----------");


            Console.WriteLine("------- Scheduling Jobs ------------------");

            string schedId = sched.SchedulerName; //sched.SchedulerInstanceId;

            int count = 1;


            IJobDetail job = JobBuilder.Create<SimpleRecoveryJob>()
                .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                .Build();


            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                                          .WithIdentity("triger_" + count, schedId)
                                                          .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second))
                                                          .WithSimpleSchedule(x => x.WithRepeatCount(1000).WithInterval(TimeSpan.FromSeconds(5)))
                                                          .Build();
            Console.WriteLine("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds);
            sched.ScheduleJob(job, trigger);

            count++;


            job = JobBuilder.Create<SimpleRecoveryJob>()
                .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                           .WithIdentity("triger_" + count, schedId)
                                           .StartAt(DateBuilder.FutureDate(2, IntervalUnit.Second))
                                           .WithSimpleSchedule(x => x.WithRepeatCount(1000).WithInterval(TimeSpan.FromSeconds(5)))
                                           .Build();

            Console.WriteLine(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));
            sched.ScheduleJob(job, trigger);
            // jobs don't start firing until start() has been called...
            Console.WriteLine("------- Starting Scheduler ---------------");
            sched.Start();
            Console.WriteLine("------- Started Scheduler ----------------");

            Console.WriteLine("------- Waiting for one hour... ----------");

            Thread.Sleep(TimeSpan.FromHours(1));


            Console.WriteLine("------- Shutting Down --------------------");
            sched.Shutdown();
            Console.WriteLine("------- Shutdown Complete ----------------");
        }

測試添加兩個job,每隔5s執行一次。

在圖中可以看到:job1和job2不會重覆執行,當我停了Job2時,job2也在job1當中運行。

這樣就可以實現分散式部署時的問題了,Quzrtz.net的資料庫結構隨便網上找一下,運行一些就好了。

截取幾個資料庫的數據圖:基本上就存儲了一些這樣的信息
JobDetail

觸發器的數據

這個是調度器的

這個是鎖的

下一期:

1.Job的介紹:有狀態Job,無狀態Job。
2.MisFire
3.Trigger,Cron介紹
4.第一部分的改造,自己實現一個基於在HostedService能夠進行分散式調度的Job類,其實只要實現了這個,其他的上面講的都沒有問題。棄用Quartz的表的行級鎖。因為這併發高了比較慢!!

個人問題

個人還是沒有測試出來這個RequestRecovery。怎麼用過的!!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 安裝 目前很多項目都需要用到composer管理,這裡主要介紹一下在Windows下如何安裝composer。 首先下載Composer-Setup.exe,下載地址:https://getcomposer.org/download/。 點擊安裝,這裡註意一點,選擇developer mode可以自 ...
  • 效果展示: 此模板主要用於多線程套圖下載,不過一般大眾爬蟲不用破譯的都可以改改使用,附件有個美圖錄的例子。 每個用途 每個網址 細節都會有差異 所有帶(*)的都屬於DIY範疇,需要一些基本的html知識,請靈活使用。 添加了斷點續傳功能,文件夾名稱改為套圖地址; 每一句Python源代碼後面都有詳細 ...
  • 文章目錄: 事物的理解 壹、什麼是事物?事物的 ACID(Atomicity 、Consistency 、Durability、Isolation )? 貳、臟讀、不可重覆讀、幻讀? 叄、事物的隔離級別? 深入理解 Spring 事務原理 壹、事務的基本原理 貳、Spring 事務的傳播屬性 叄、數 ...
  • 判斷語句主要有if...else、switch和 條件?語句1:語句2 三種,而if...else中又有if語句,if...else、if...else if...else和if中嵌套if這幾種,但是只要掌握if...else if...else語句其他if類型語句的用法都是相似的 if...els ...
  • 線程的等待時可以用這個,不論是線程池還是線程都可以用這個做等待。 當然也可以用迴圈待等的執行的方式進行線程待等 ...
  • WebJobs不是Azure和.NET中的新事物。 Visual Studio 2017中甚至還有一個預設的Azure WebJob模板,用於完整的.NET Framework。 但是,Visual Studio中以某種方式遺漏了.NET Core中WebJobs的類似模板。 在這篇文章中,我使用的 ...
  • 準備寫一些關於Identity4相關的東西,最近也比較對這方面感興趣。所有做個開篇筆記記錄一下,以便督促自己下一個技術方案方向 已經寫好的入門級別Identity4的服務+api資源訪問控制和簡單的客戶端請求模擬: 1.實現服務端+api資源控制+客戶端請求 2.後面準備寫單點登錄統一認證服務 ...
  • 1. NUGET包引用 icrosoft.AspNetCore.Session 2.Startup中添加一下代碼: 3.控制器中使用Session using Microsoft.AspNetCore.Http; //添加引用 HttpContext.Session.SetString("key", ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...