定时任务Job和SpringBatch批处理结合

什么不多说直接上Demo:

vo类:

package it.quartz.job.test;

import java.io.Serializable;
import java.util.Date;

public class SelVo implements Serializable{
	private static final long serialVersionUID = 2746434425903993053L;
	private String name;
	private Date testDate;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getTestDate() {
		return testDate;
	}
	public void setTestDate(Date testDate) {
		this.testDate = testDate;
	}
	
}

Job任务类:

package it.quartz.job.test;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyFirstJob {
	
	private final String contextPath = PathHelper.getWEB_INF_Path()+"conf/quartz-test.xml";
	private ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"file:"+contextPath});
	public void excute(){
		System.out.print(new SimpleDateFormat("YYYY-mm-dd HH:mm:ss").format(new Date())+"========Spring Job Hello World!");
		SimpleJobLauncher launcher = (SimpleJobLauncher) ac.getBean("testLuncher");
		Job job = (Job) ac.getBean("testJob");
		JobParametersBuilder builder = (JobParametersBuilder) ac.getBean("paramsBuilder");
		builder.addDate("date", new Date());
		
		try {
			launcher.run(job, builder.toJobParameters());
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}

RowMapper实现类:

package it.quartz.job.test;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;


public class MyRowMapper implements RowMapper<SelVo>{

	@Override
	public SelVo mapRow(ResultSet rs, int i)
			throws SQLException {
		SelVo selVo = new SelVo();
		selVo.setName(rs.getString("name"));
		selVo.setTestDate(rs.getTimestamp("testDate"));
		return selVo;
	}

}

读到写的过程类:

package it.quartz.job.test;

import org.springframework.batch.item.ItemProcessor;

public class MyProcessor implements ItemProcessor<SelVo, SelVo>{

	@Override
	public SelVo process(SelVo selVo) throws Exception {
		return selVo;
	}

}

获取web-inf路径的工具类:

package it.quartz.job.test;


public class PathHelper  {

	public static String getWEB_INF_Path(){
		String osName = System.getProperty("os.name");
		System.out.println("judging os system to be :"+osName);
		String configPath = PathHelper.class.getResource("/").getPath();	
		if(configPath == null){
			throw new RuntimeException("config path cannot be null");
		}
		if(osName.toLowerCase().contains("windows")){
			configPath = configPath.replaceFirst("/", "");
			configPath = configPath.replaceFirst("classes/", "");
		}else{
			configPath = configPath.replaceFirst("classes/", "");
		}		
		return configPath;
	}

}

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringBatch</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/conf/job-test.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

定时任务配置文件:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:cache="http://www.springframework.org/schema/cache" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd  
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 调度器 -->
    <bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <!-- 触发器列表 -->
        <property name="triggers">
            <list>
                <ref bean="connTrigger"/>
            </list>
        </property>
    </bean>
    
    <!-- 触发器 -->
    <bean id="connTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <!-- 处理类中转工厂 -->
        <property name="jobDetail" ref="myJobDetail"/>
        <property name="cronExpression" value="0 */1 * * * ?"/>
    </bean>
    
    <!-- 处理类中转工厂  -->
    <bean id="myJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 处理类 -->
        <property name="targetObject" ref="myJob"/>
        <property name="targetMethod" value="excute"/>
        <property name="concurrent" value="false"/>
    </bean>
    
    <bean id="myJob" class="it.quartz.job.test.MyFirstJob"/>
</beans>

spring批处理配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/batch"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/batch
    http://www.springframework.org/schema/batch/spring-batch-2.1.xsd">
    
    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <beans:property name="url" value="jdbc:oracle:thin:@:orcl"/>
        <beans:property name="username" value=""/>
        <beans:property name="password" value=""/>
    </beans:bean>
    
    <beans:bean id="testLuncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <beans:property name="jobRepository" ref="jobRepo"/>
    </beans:bean>
    
    <beans:bean id="paramsBuilder" class="org.springframework.batch.core.JobParametersBuilder"/>
    
    <beans:bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <beans:property name="dataSource" ref="dataSource"/>
    </beans:bean>
    
    <beans:bean id="jobRepo" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="databaseType" value="oracle"/>
        <beans:property name="transactionManager" ref="transactionManager"/>
    </beans:bean>
    
    <beans:bean id="rowMapper" class="it.quartz.job.test.MyRowMapper"/>
    
    <beans:bean id="testReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="rowMapper" ref="rowMapper"/>
        <beans:property name="sql" value="select emp.EMP_NAME name, emp.CREATED_TIME testDate from AU_EMPLOYEE emp where emp.id = '1099104500000000025'"/>    
    </beans:bean>    
    
    <beans:bean id="testWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="itemSqlParameterSourceProvider" ref="testItemSqlParameterSourceProvider"/>
        <beans:property name="sql" value="update AU_EMPLOYEE emp set emp.PERSON_NAME = :name where emp.id = '1099104500000000025'"/>
    </beans:bean>    
    
    <beans:bean id="testItemSqlParameterSourceProvider" class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    
    <beans:bean id="testProcessor" class="it.quartz.job.test.MyProcessor"/>
    
    <job id="testJob" job-repository="jobRepo" restartable="true">
        <step id="testStep">
            <tasklet>
                <chunk reader="testReader" processor="testProcessor" writer="testWriter" commit-interval="10000" skip-limit="10000">
                    <skippable-exception-classes></skippable-exception-classes>
                </chunk>
            </tasklet>
        </step>
    </job>
</beans:beans >

cronExpression:* * * * * ?

* 代表任意

?代表年份

比如:0 */1 * * * ? 每一分钟的0秒执行一次

           0 0 */1 * * ? 每一小时的0分0秒执行一次

           0 0 23 L * ? 每月最后一天23点执行一次(L:最后的意思)

    上面的spring批处理配置有点瑕疵哦,如果数据库是Oracle的话,JobRepositoryFactoryBean还要多加个属性'isolationLevelForCreate',完整的如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/batch"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/batch
    http://www.springframework.org/schema/batch/spring-batch-2.1.xsd">
    <!-- 引入dataSource -->
    <beans:import resource="applicationContext.xml"/>
    
    <beans:bean id="jobLuncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <beans:property name="jobRepository" ref="mealcardRepo"/>    
    </beans:bean>
    
    <beans:bean id="jobParamsBuilder" class="org.springframework.batch.core.JobParametersBuilder"/>
    
    <beans:bean id="transactionManager2"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <beans:property name="dataSource" ref="dataSource"/>
    </beans:bean>
    
    <beans:bean id="mealcardRepo" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="isolationLevelForCreate" value="ISOLATION_READ_COMMITTED"/>  
        <beans:property name="transactionManager" ref="transactionManager2"/>  
        <beans:property name="databaseType" value="oracle"/>  
    </beans:bean>    
    
    <beans:bean id="mealcardRowMapper" class="gap.mealcard_quancun.quartz.data.MealcardRowMapper"/>
    
    <beans:bean id="mealcardReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="rowMapper" ref="mealcardRowMapper"/>
        <beans:property name="sql" value="" />
    </beans:bean>
    
    <beans:bean id="mealCardProcessor" class="gap.mealcard_quancun.quartz.util.MealCardProcessor"/>
    
    <beans:bean id="mealcardWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
        <beans:property name="dataSource" ref="dataSource"/>
        <beans:property name="itemSqlParameterSourceProvider" ref="mealcardItemParamProvider"/>
        <beans:property name="sql" value=""/>
    </beans:bean>    
    
    <beans:bean id="mealcardItemParamProvider" class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    
    <job id="mealcardJob" restartable="true" job-repository="mealcardRepo">
        <step id="mealCardStep">
            <tasklet transaction-manager="transactionManager2" allow-start-if-complete="true" start-limit="3">
                <chunk reader="mealcardReader" processor="mealCardProcessor" writer="mealcardWriter" commit-interval="10000" skip-limit="10000">
                    <skippable-exception-classes>
                        <include class="java.sql.SQLException" />
                        <include class="org.springframework.dao.DataIntegrityViolationException" />  
                    </skippable-exception-classes>
                </chunk>
            </tasklet>
        </step>
    </job>
</beans:beans>

    事务隔离级别'ISOLATION_READ_COMMITTED'是要配的,因为Job工厂的默认事务隔离级别是'ISOLATION_SERIALIZABLE',这个事务级别在Job里很容易出现'无法连续访问此事务处理的异常'。

    喜欢此文的朋友请点个赞哦!

转载于:https://my.oschina.net/wliming/blog/688240

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值