Springboot2統合クォーツ動的タスク管理+ Web UI



Spring Boot2 Integrated Quartz Dynamic Task Management Web Ui

最近会社にインターンし、会社には春とクォーツの動的タスク管理システムのセットがあることがわかりました。 Webインターフェイスを使用して、タスクを動的に作成、削除、停止、実行、および変更できます。最近、春のブーツを学びました。次に、spring boot2 + quartz + thymeleaf + mysqlデータベースを使用して、単純な動的タスク管理システムを実装します。

プロジェクトの使用方法:

IDEAを使用してプロジェクトを開き、application.propertiesのデータ情報を独自のデータ情報に変更します。同時に、sqlフォルダー内のsqlファイルをデータにインポートできます。プロジェクトアドレス: http:// localhost:8080 /



プロジェクトアドレスGithubアドレス: Quartz動的タスクスケジューリングシステム

プロジェクトを以下に示します。
画像



石英

Quartzは、Javaで記述されたオープンソースのタスクスケジューリングフレームワークです。その主なスケジューリング要素は次のとおりです。

  • トリガー(トリガー):タスクの実行をトリガーする時間またはルール。タスクスケジューリングQuartzでは、Triggerの主なトリガーはSimpleTrigger、CalendarIntervelTrigger、DailyTimeIntervalTrigger、CronTriggerです。
  • スケジューラー(タスクスケジューラー):スケジューラーはタスクスケジューリングコントローラーです。実行する前に、スケジュールにJobDetailとTriggerを登録する必要があります。スケジューラーには、ThreadPoolとJobStoreの2つの重要なコンポーネントがあります。
  • ジョブ(タスク):実行メソッドが1つしかないインターフェースです。開発者は、インターフェイスにexecuteメソッドを実装するだけで済みます。
  • JobDetail(タスクの詳細):Quartzがジョブを実行するとき、新しいJobインスタンスを作成する必要がありますが、Jobクラスを直接操作することはできないため、ジョブの名前と説明の情報はJobDetailから取得されます。

オブジェクト間の関係図を次の図に示します。

画像



画像

スプリングブーツ2一体型クォーツ

  1. クォーツ依存関係を追加

    <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-quartzartifactId> dependency>
  2. Spring Boot2 Web、thymeleaf、依存関係を追加します

    <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-websocketartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency>

    その他の詳細については、githubプロジェクトのpomファイルを参照してください。

  3. 関連する属性構成ファイル。

    # Database connection configuration spring.datasource.druid.url=jdbc:mysql://localhost:3306/dynamicquartz?useUnicode=true&characterEncoding=utf8 spring.datasource.druid.username=root spring.datasource.druid.password=2012061128 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.filters=stat spring.datasource.druid.max-active=20 spring.datasource.druid.initialSize=1 spring.datasource.druid.max-wait=60000 spring.datasource.druid.min-idle=1 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.validation-query=select 'x' spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-return=false spring.datasource.druid.test-on-borrow=false # mybatis configuration mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=cn.bupt.zcc.dynamicquartz.model # quartz some attribute configuration spring.quartz.job-store-type=jdbc spring.quartz.properties.org.quartz.scheduler.instanceName=clusteredScheduler spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate spring.quartz.properties.org.quartz.jobStore.tablePrefix=QRTZ_ #spring.quartz.properties.org.quartz.jobStore.isClustered=true #spring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=10000 spring.quartz.properties.org.quartz.jobStore.useProperties=false # Integrate some configuration of thymeleaf engine spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.check-template-location=true spring.thymeleaf.suffix=.html spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type=text/html spring.thymeleaf.mode=HTML5 spring.thymeleaf.cache=false
  4. クォーツタスクファクトリクラスQuartzJobFactoryを作成します。

    /** * @author: Zhang Chengcheng * @create: 2018-05-31 14:38 **/ @Service('quartzJobFactory') public class QuartzJobFactory extends QuartzJobBean { @Autowired QuartzService quartzService @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { ScheduleJob object = (ScheduleJob) jobExecutionContext.getMergedJobDataMap().get('scheduleJob') if(object.getMethodName()==null || object.getMethodName().equals('')){ quartzService.executeTask(object.getBeanName()) }else { quartzService.executeTask(object.getBeanName(),object.getMethodName()) } } }

    これは、QuartzJobBeanクラスを継承するタスクファクトリクラスです。動的に追加される各時限タスクは、そのようなインスタンスを作成することです。そして、実行するようにスケジュールされたタスククラスの名前、または完全修飾クラス名と実行するメソッドの名前を渡します。 QuartzServiceは、着信Spring Beanの名前または完全修飾クラス名を取得し、タスククラスの名前を取得し、リフレクションを使用してメソッドを呼び出してタスクを実行します。実行するタスククラスを、リフレクションを介してJobインターフェイスまたはQuartzJobBeanクラスから切り離します。タスククラスは、Jobインターフェイスを実装したり、QuartzJobBeanクラスを統合したりする必要はありません。タスクの動的スケジューリングを実現できます。

  5. QuartzService実装クラスは次のとおりです。

    /** * @author: Zhang Chengcheng * @create: 2018-05-31 15:34 **/ @Service('quartzService') public class QuartzServiceImpl implements QuartzService { private static final Logger logger = LoggerFactory.getLogger(QuartzServiceImpl.class) private static final String METHODNAME = 'execute' @Override public void executeTask(String beanName, String methodName) { Object object = ApplicationContextUtil.getBean(beanName) try { logger.info('[QuartzServiceImpl] reflex beanName:{},methodName:{}method start.........',beanName,methodName) if (beanName.contains('\.')){ Class clazz = Class.forName(beanName) Object cronJob = ApplicationContextUtil.getBean(clazz) Method method1 = clazz.getMethod(methodName) method1.invoke(cronJob) }else { Method method = object.getClass().getMethod(methodName) method.invoke(object) } } catch (Exception e) { logger.error('[QuartzServiceImpl] method invoke error,beanName:{},methodName:{}',beanName,methodName) return } logger.info('[QuartzServiceImpl] reflex beanName:{},methodName:{}method ends...',beanName,methodName) }
  6. ApplicationContextUtilは、SpringBeanインスタンスを取得するためのツールクラスです。

    /** * * @author: Zhang Chengcheng * @create: 2018-05-31 15:07 **/ @Component('ApplicationContextUtil') public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtil.applicationContext = applicationContext } public ApplicationContext getApplicationContext(){ checkApplicationContext() return applicationContext } public void checkApplicationContext(){ if (applicationContext==null){ throw new IllegalStateException('applicationContext is not injected, please define SpringContextUtil in applicationContext.xml') } } /** *Find an instance of a class based on the bean name * @param name * @param * @return */ public static T getBean(String name){ return (T) applicationContext.getBean(name) } }

    ApplicationContextUtilクラスは、ApplicationContextAwareインターフェイスを実装することによってapplicationContextコンテキストを取得します。したがって、タスクのインスタンスを反映して取得します。次に、リフレクションを介してタスクを実行します。

  7. タスクを動的に追加する

    private void addJob(ScheduleJob scheduleJob) throws Exception{ checkNotNull(scheduleJob) if (StringUtils.isBlank(scheduleJob.getCronExpression())){ throw new Exception('[SchedulerJobServiceImpl] CronExpression cannot be empty') } scheduleJob.setJobStatus('NORMAL') int id = scheduleJobInService.insertSelective(scheduleJob) logger.info('[SchedulerJobServiceImpl] the Primary key is:{}',scheduleJob.getId()) scheduleJob.setJobId(scheduleJob.getId()+'') logger.info('[SchedulerJobServiceImpl] the scheduleJob is:{}',scheduleJob) scheduleJobInService.updateByPrimaryKey(scheduleJob) JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(scheduleJob.getJobName(),scheduleJob.getJobGroup()) .build()//Create JobDetail, job is created by QuartzJobFactory.class factory class reflection. jobDetail.getJobDataMap().put('scheduleJob',scheduleJob) CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(),scheduleJob.getJobGroup()) .withSchedule(cronScheduleBuilder).build()//Create trigger scheduler.scheduleJob(jobDetail,cronTrigger)//Register jobDetail and Trigger for task scheduling. }
  8. Webインターフェースを使用して、タスクの動的な追加を実現します。 thymeleafエンジンが使用されます。

    画像

参照:

https://github.com/jiwenxing/springboot-quartz 「スプリングブーツクォーツ」

https://www.jianshu.com/p/5995937f27bc 「クォーツチュートリアル」

https://blog.csdn.net/u012907049/article/details/73801122 「SpringBoot統合された永続的なQuartzタイミングタスク管理とインターフェース表示」