zoukankan      html  css  js  c++  java
  • 使用mongodb作为Quartz.Net下的JobStore实现底层的持久化机制

      我们都知道默认的Quartz底层采用的是RAMJobStore,所有的Job,Trigger,Calendar都是用Dictionary,SortSet等等这样的数据结构进行储存,相对来说性

    能肯定快的没法说,但是面对灾难重启的时候还是很拿不出手的,而且都是全内存的,也没法实现多机器搭建Quartz集群,这一点还是很讨厌,虽然官方已经

    提供了一些关系性持久化存储方案,但面对如今这么火的nosql,不进行官方支持还是有点可惜,不过基于Quartz本身的插拔式设计,一切都不是问题。

    一:IJobStore

       从github上下载源码:https://github.com/quartznet/quartznet,从源码你会发现IJobStore几乎实现了所有对Trigger,Job和Scheduler所有的容器管理操作。

    然后你可以看到它的几个实现子类,全内存的RAMJobStore。

    public class RAMJobStore: IJobStore
    {
    ....
    }

    以及JobStoreSupport下的带锁JobStoreTX和不带锁的JobStoreCMT。

    public class JobStoreSupport: IJobStore
    {
    ....
    }
    
    //带锁机制
    public class JobStoreTX: JobStoreSupport
    {
    ....
    }
    
    //不带锁
    public class JobStoreCMT: JobStoreSupport
    {
    ....
    }

    所以你应该明白,本节课跟大家讲到的Redis和Mongodb的JobStore存储,必然也是实现了IJobStore接口,对吧。

    二:MongoDB的JobStore

    1. 安装mongodb

         既然要使用mongodb,你必然要有mongodb的安装程序,可以去官网: wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.5.tgz 一下,

    这里我采用linux平台的centos。

    2. nuget上pull些dll

        大家可以在nuget控制台执行Install-Package Quartz.Spi.MongoDbJobStore,如下所示:

    PM> Install-Package Quartz.Spi.MongoDbJobStore
    正在尝试收集与目标为“.NETFramework,Version=v4.5.2”的项目“ConsoleApplication1”有关的包“Quartz.Spi.MongoDbJobStore.2.0.0”的依赖项信息
    正在尝试解析程序包“Quartz.Spi.MongoDbJobStore.2.0.0”的依赖项,DependencyBehavior 为“Lowest”
    正在解析操作以安装程序包“Quartz.Spi.MongoDbJobStore.2.0.0”
    已解析操作以安装程序包“Quartz.Spi.MongoDbJobStore.2.0.0”
    正在将程序包“Common.Logging.Core.3.3.1”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Common.Logging.Core.3.3.1”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Common.Logging.Core.3.3.1”添加到“packages.config”
    已将“Common.Logging.Core 3.3.1”成功安装到 ConsoleApplication1
    正在将程序包“Common.Logging.3.3.1”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Common.Logging.3.3.1”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Common.Logging.3.3.1”添加到“packages.config”
    已将“Common.Logging 3.3.1”成功安装到 ConsoleApplication1
    正在将程序包“MongoDB.Bson.2.4.2”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“MongoDB.Bson.2.4.2”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“MongoDB.Bson.2.4.2”添加到“packages.config”
    已将“MongoDB.Bson 2.4.2”成功安装到 ConsoleApplication1
    正在将程序包“Quartz.2.4.1”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Quartz.2.4.1”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Quartz.2.4.1”添加到“packages.config”
    已将“Quartz 2.4.1”成功安装到 ConsoleApplication1
    正在将程序包“System.Runtime.InteropServices.RuntimeInformation.4.3.0”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“System.Runtime.InteropServices.RuntimeInformation.4.3.0”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“System.Runtime.InteropServices.RuntimeInformation.4.3.0”添加到“packages.config”
    已将“System.Runtime.InteropServices.RuntimeInformation 4.3.0”成功安装到 ConsoleApplication1
    正在将程序包“MongoDB.Driver.Core.2.4.2”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“MongoDB.Driver.Core.2.4.2”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“MongoDB.Driver.Core.2.4.2”添加到“packages.config”
    已将“MongoDB.Driver.Core 2.4.2”成功安装到 ConsoleApplication1
    正在将程序包“MongoDB.Driver.2.4.2”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“MongoDB.Driver.2.4.2”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“MongoDB.Driver.2.4.2”添加到“packages.config”
    已将“MongoDB.Driver 2.4.2”成功安装到 ConsoleApplication1
    正在将程序包“Quartz.Spi.MongoDbJobStore.2.0.0”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Quartz.Spi.MongoDbJobStore.2.0.0”添加到文件夹“C:1ConsoleApplication1packages”
    已将程序包“Quartz.Spi.MongoDbJobStore.2.0.0”添加到“packages.config”
    已将“Quartz.Spi.MongoDbJobStore 2.0.0”成功安装到 ConsoleApplication1

    也可以到github中下载源码:https://github.com/chrisdrobison/mongodb-quartz-net

    3. 启动运行

        然后可以看一下此页面上的Basic Usage##上的默认配置:

     1 var properties = new NameValueCollection();
     2 properties[StdSchedulerFactory.PropertySchedulerInstanceName] = instanceName;
     3 properties[StdSchedulerFactory.PropertySchedulerInstanceId] = $"{Environment.MachineName}-{Guid.NewGuid()}";
     4 properties[StdSchedulerFactory.PropertyJobStoreType] = typeof (MongoDbJobStore).AssemblyQualifiedName;
     5 // I treat the database in the connection string as the one you want to connect to
     6 properties[$"{StdSchedulerFactory.PropertyJobStorePrefix}.{StdSchedulerFactory.PropertyDataSourceConnectionString}"] = "mongodb://localhost/quartz";
     7 // The prefix is optional
     8 properties[$"{StdSchedulerFactory.PropertyJobStorePrefix}.collectionPrefix"] = "prefix";
     9 
    10 var scheduler = new StdSchedulerFactory(properties);
    11 return scheduler.GetScheduler();

     <1>  PropertySchedulerInstanceName: 就是对Scheduler的Name进行的配置,大家可以根据情况定义一个简明释义的名字。

     <2> PropertySchedulerInstanceId: 可以看到这个项采用的是machineName+NewGuid来保证Scheduler容器的SchedulerID唯一,唯一性特别重要,因为在

                     Cluster 中就是用它来保证唯一性的,不过上面的代码有点累赘,其实只要写上“AUTO”就可以了,由底层的

                               SimpleInstanceIdGenerator来保证uniqueID的生成,如StdSchedulerFactory.Instantiate方法源码所示:

     1             if (schedInstId.Equals(AutoGenerateInstanceId))
     2             {
     3                 autoId = true;
     4                 instanceIdGeneratorType = LoadType(cfg.GetStringProperty(PropertySchedulerInstanceIdGeneratorType)) ?? typeof(SimpleInstanceIdGenerator);
     5             }
     6             else if (schedInstId.Equals(SystemPropertyAsInstanceId))
     7             {
     8                 autoId = true;
     9                 instanceIdGeneratorType = typeof(SystemPropertyInstanceIdGenerator);
    10             }

    <3> PropertyJobStoreType:这个属性将MongoDbJobStore作为底层的IJobStore实现者。

    <4> PropertyDataSourceConnectionString,collectionPrefix: 这两个没什么好说的,一个是mongodb的connectionstring,一个是collection的前缀。

    好了,下面就是我的完整代码:

     1         static void Main(string[] args)
     2         {
     3 
     4             LogManager.Adapter = new Common.Logging.Simple.TraceLoggerFactoryAdapter()
     5             {
     6                 Level = LogLevel.All
     7             };
     8 
     9             var properties = new NameValueCollection();
    10             properties[StdSchedulerFactory.PropertySchedulerInstanceId] = "AUTO";
    11             properties[StdSchedulerFactory.PropertyJobStoreType] = typeof(MongoDbJobStore).AssemblyQualifiedName;
    12 
    13             // I treat the database in the connection string as the one you want to connect to
    14             properties[$"{StdSchedulerFactory.PropertyJobStorePrefix}.{StdSchedulerFactory.PropertyDataSourceConnectionString}"] = "mongodb://192.168.23.163/quartz";
    15 
    16             // The prefix is optional
    17             properties[$"{StdSchedulerFactory.PropertyJobStorePrefix}.collectionPrefix"] = "prefix";
    18 
    19             var factory = new StdSchedulerFactory(properties);
    20 
    21             //scheduler
    22             IScheduler scheduler = factory.GetScheduler();
    23 
    24             scheduler.Start();
    25 
    26             var job = JobBuilder.Create<HelloJob>().WithIdentity("test", "datamip").Build();
    27 
    28             var trigger = TriggerBuilder.Create().WithCronSchedule("* * * * * ?").Build();
    29 
    30             if (!scheduler.CheckExists(job.Key))
    31             {
    32                 scheduler.ScheduleJob(job, trigger);
    33             }
    34 
    35             Console.Read();
    36         }

    这个我自定义的HelloJob中,我特意记录一下scheduler的调度时间schedulertime和Trigger应该触发的时间nextFireTime。

     1     class HelloJob : IJob
     2     {
     3         static int index = 1;
     4 
     5         public void Execute(IJobExecutionContext context)
     6         {
     7             Console.WriteLine("{4} index={0},current={1}, scheuler={2},nexttime={3}",
     8                                             index++, DateTime.Now,
     9                                             context.ScheduledFireTimeUtc?.LocalDateTime,
    10                                             context.NextFireTimeUtc?.LocalDateTime,
    11                                             context.JobDetail.JobDataMap["key"]);
    12         }
    13     }

    接下来执行一下:

    然后通过robomongo到数据库看一下,有5个collection,里面都有数据,没毛病。

    好了,本篇就说到这里了,当然还有基于redis的JobStore,有兴趣大家可以自己尝试一下。

  • 相关阅读:
    String类的常用方法
    StringBuffer和String的区别
    docker安装kali
    6.找素数
    5.三羊献瑞
    4.迷宫大逃亡
    3.百米
    2.后台登录
    1.猴子吃桃
    深入理解Docker容器和镜像
  • 原文地址:https://www.cnblogs.com/huangxincheng/p/7078895.html
Copyright © 2011-2022 走看看