我们先让代码跑起来,来一个简单的例子。
一、引入jar包
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-core</artifactId>
<version>2.1.5</version>
</dependency>
<!-- 这里要注意,我们和Spring集成,要引入这个jar包 -->
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-spring</artifactId>
<version>2.1.5</version>
</dependency>
二、代码开发
1.配置文件
在/Davis/src/main/resources/目录下增加spring-job目录,并新建文件spring-job.xml。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:reg="http://www.dangdang.com/schema/ddframe/reg"
xmlns:job="http://www.dangdang.com/schema/ddframe/job"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.dangdang.com/schema/ddframe/reg
http://www.dangdang.com/schema/ddframe/reg/reg.xsd
http://www.dangdang.com/schema/ddframe/job
http://www.dangdang.com/schema/ddframe/job/job.xsd
">
<!--配置作业注册中心 zookeeper_url=10.136.19.170:2181,zookeeper_namespace=elastic-job这个可以自己任意起名字 -->
<reg:zookeeper id="regCenter"
server-lists="${zookeeper_url}"
namespace="${zookeeper_namespace}"
base-sleep-time-milliseconds="1000"
max-sleep-time-milliseconds="3000"
max-retries="3" />
<!-- 配置作业 -->
<job:simple id="demoSimpleSpringJob" class="com.spring.lw.job.UserElasticJob"
registry-center-ref="regCenter"
cron="0/10 * * * * ?"
sharding-total-count="3"
sharding-item-parameters="0=A,1=B,2=C" />
</beans>
2.代码
package com.spring.lw.job;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
public class UserElasticJob implements SimpleJob {
@Override
public void execute(ShardingContext context) {
// TODO Auto-generated method stub
switch (context.getShardingItem()) {
case 0:
System.out.println("UserElasticJob execute context = " + 0);
break;
case 1:
System.out.println("UserElasticJob execute context = " + 1);
break;
case 2:
System.out.println("UserElasticJob execute context = " + 2);
break;
// case n: ...
}
}
}
3.运行
放到Tomcat跑一下看看,当然zookeeper要先启动起来。
控制台会输出:
UserElasticJob execute context = 0
UserElasticJob execute context = 1
UserElasticJob execute context = 2
反正是跑起来了,虽然到现在看起来没什么卵用。
我们把这个工程部署到两个Tomcat试试,启动两个Tomcat,会发现。
Tomcat1的控制台输出:
UserElasticJob execute context = 0
UserElasticJob execute context = 2
Tomcat2的控制台输出:
UserElasticJob execute context = 1
好像体会到一点好处了。