Spring應(yīng)用接入SchedulerX
您可以為您的Spring應(yīng)用快速接入SchedulerX,實(shí)現(xiàn)分布式任務(wù)調(diào)度能力。
前提條件
(可選)已創(chuàng)建命名空間。具體操作,請(qǐng)參見創(chuàng)建命名空間。
已創(chuàng)建資源。具體操作,請(qǐng)參見創(chuàng)建資源。
Spring應(yīng)用客戶端接入SchedulerX
在應(yīng)用程序的
pom.xml
文件中添加SchedulerxWorker依賴。請(qǐng)參見客戶端發(fā)布記錄,
schedulerx2.version
使用最新客戶端版本。<dependency> <groupId>com.aliyun.schedulerx</groupId> <artifactId>schedulerx2-worker</artifactId> <version>${schedulerx2.version}</version> <!--如果用的是logback,需要把log4j和log4j2排除掉 --> <exclusions> <exclusion> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> </exclusion> <exclusion> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency>
在xml配置文件中初始化SchedulerxWorker(注入Bean)。
初始化SchedulerxWorker時(shí),會(huì)用到您部署應(yīng)用的地域(Region)和對(duì)應(yīng)的Endpoint。詳情請(qǐng)參見Endpoint列表。
namespace為命名空間ID,可以在控制臺(tái)命名空間頁面獲取。
groupId為應(yīng)用ID,appKey為應(yīng)用key,可以在控制臺(tái)應(yīng)用管理頁面獲取。您也可以在操作列,單擊接入配置獲取對(duì)應(yīng)接入方式的配置信息。
<bean id="schedulerxWorker" class="com.alibaba.schedulerx.worker.SchedulerxWorker"> <property name="endpoint"> <value>${endpoint}</value> </property> <property name="namespace"> <value>${namespace}</value> </property> <property name="groupId"> <value>${groupId}</value> </property> <!--1.2.1及以上版本設(shè)置appKey --> <property name="appKey"> <value>${appKey}</value> </property> </bean>
說明一個(gè)應(yīng)用如果包含多個(gè)業(yè)務(wù),或者想把定時(shí)任務(wù)進(jìn)行歸類,可以建立多個(gè)分組,例如應(yīng)用
animals
建了兩個(gè)分組animals.dogs
和animals.cats
。此時(shí)不用申請(qǐng)兩批實(shí)例分別接入這兩個(gè)分組,在應(yīng)用客戶端中將這兩個(gè)分組配置到groupId=
后面即可,例如groupId=animals.dogs,animals.cats
。在初始化SchedulerxWorker客戶端時(shí),如果還有其它配置需求,可以參考SchedulerxWorker配置參數(shù)說明添加配置。
在應(yīng)用中創(chuàng)建類
JobProcessor
,實(shí)現(xiàn)任務(wù)調(diào)度。本文僅介紹如何實(shí)現(xiàn)一個(gè)最簡單的定時(shí)打印“Hello SchedulerX2.0”的
JobProcessor
類。package com.aliyun.schedulerx.test.job; import com.alibaba.schedulerx.worker.domain.JobContext; import com.alibaba.schedulerx.worker.processor.JavaProcessor; import com.alibaba.schedulerx.worker.processor.ProcessResult; @Component public class MyHelloJob extends JavaProcessor { @Override public ProcessResult process(JobContext context) throws Exception { System.out.println("hello schedulerx2.0"); return new ProcessResult(true); } }
結(jié)果驗(yàn)證
客戶端接入完成,將該應(yīng)用發(fā)布到阿里云。
登錄分布式任務(wù)調(diào)度平臺(tái),在頂部菜單欄選擇地域,然后在左側(cè)導(dǎo)航欄,單擊應(yīng)用管理,在應(yīng)用管理頁面查看實(shí)例總數(shù)。
如果實(shí)例總數(shù)為0,說明應(yīng)用接入失敗。請(qǐng)檢查、修改本地應(yīng)用。
如果實(shí)例總數(shù)不為0,顯示接入的實(shí)例個(gè)數(shù),說明應(yīng)用接入成功。在操作列單擊查看實(shí)例,即可在連接實(shí)例對(duì)話框中查看實(shí)例列表。
后續(xù)步驟
應(yīng)用接入SchedulerX完成后,即可在分布式任務(wù)調(diào)度平臺(tái)創(chuàng)建調(diào)度任務(wù)。更多信息,請(qǐng)參見創(chuàng)建調(diào)度任務(wù)。