1. 程式人生 > >spring batch之二 一個簡單的spring batch的例子.

spring batch之二 一個簡單的spring batch的例子.

在實際工作中我們可能需要快速的實現一個spring batch.本文作為一個參考例子。 主要使用maven ,STS tool.   spring.framework.version 3.0.6.RELEASE. spring.batch.version 2.1.7.RELEASE mysql database. 

1: spring maven pom

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples.batch</groupId>
<artifactId>spring-batch-simple</artifactId>
<version>2.0.0.CI-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Command Line Spring Batch Module</name>
<url>http://www.springframework.org/spring-batch/archetypes/simple-cli-archetype</url>
<properties>
<maven.test.failure.ignore>true</maven.test.failure.ignore>
<spring.framework.version>3.0.6.RELEASE</spring.framework.version>
<spring.batch.version>2.1.7.RELEASE</spring.batch.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>${spring.batch.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-infrastructure</artifactId>
<version>${spring.batch.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>


<pluginRepositories>
<pluginRepository>
<id>Codehaus</id>
<url>http://repository.codehaus.org/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

在mysql database 建立spring batch 系列表.

解壓縮spring-batch-code-2.1.7-RELEASE.jar 在  org.springframework.batch.core 包下找到schema-mysql.sql. 在mysql database中執行該檔案,建立spring 相關的表.

在mysql中建立student 表

建立student 表,主要包含id, name,age

spring batch 配置,將所有學生的age+1

   <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" >
<value><![CDATA[jdbc:mysql://192.168.0.1:3306/test?characterEncoding=UTF-8]]></value>
</property>
<property name="username" value="xxx" />
<property name="password" value="xxxxxx" />
</bean>

      <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

  <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">

<property name="dataSource" ref="dataSource"/>
<property name="transactionManager" ref="transactionManager"/>
  </bean>
  

 <bean id="jobLauncher"  class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
 <property name="jobRepository" ref="jobRepository"></property>
 </bean>

   <batch:job id="job1">
        <batch:step id="step1">
            <batch:tasklet transaction-manager="transactionManager">
               <batch:transaction-attributes
                        isolation="DEFAULT" propagation="REQUIRED" timeout="3" />
                 <batch:chunk reader="itemReader1"
                              processor="itemProcessor1" writer="itemWriter1"
                         commit-interval="2">
              </batch:chunk>
         </batch:tasklet>
    </batch:step>
</batch:job>

<bean id="itemReader1"
class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="dataSource" />
<property name="rowMapper" ref="studentMapper" />
<property name="sql"
value="select * from student" />
</bean>


<bean id="itemProcessor1"
class="com.springbatch.demo.item.StudentProcessor">
</bean>


<bean id="itemWriter1"
class="com.springbatch.demo.item.StudentWriter"
scope="step">
<property name="inventoryAdjustmentInDao" ref="inventoryAdjustmentInDao" />
<property name="inventoryDao" ref="inventoryDao" />
<property name="wareHouseCode" value="#{jobParameters['ware_house']}" />
<property name="workItem" value="#{jobParameters['work_item']}"></property>
</bean>


<bean id="studentMapper"
class="com.springbatch.demo.dao.rowmapper.StudentRowMapper">
<property name="mappedClass"
value="com.springbatch.demo.entity.Student"></property>
</bean>

     ............................

</beans>

item processor 和 item writer

package com.springbatch.demo.item;

import org.springframework.batch.item.ItemProcessor;
import com.springbatch.demo.entity.Student;
public class StudentProcessor implements ItemProcessor<Student, Student> {

    @Override
    public InventoryAdjustmentIn process(final Student student) throws Exception {
student.setAge(student.getAge()+1);
return student;
    }
}

package com.springbatch.demo.item;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.batch.item.ItemWriter;
import com.springbatch.demo.dao.StudentDao;
import com.springbatch.demo.entity.Student;


public class StudentWriter implements ItemWriter<Student> {

    private StudentDao studentDao;

    @Override
    public void write(final List<? extends Student> students) throws Exception {

for (Student item : students) {
studentDao.update(item);
}
    }
}

main test class

package com.vipshop.springbatch.demo.pl3;


import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class studentTest {


    public static void main(final String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("launch-context.xml");
JobLauncher jobLauncher = context.getBean("jobLauncher", JobLauncher.class);
Job job = context.getBean("pl3-repository-adjust", Job.class);
JobParameters jobParam = new JobParametersBuilder().addString("test", "test1")
.addLong("currenttime", System.currenttime).toJobParameters();
try {
   jobLauncher.run(job, jobParam);
}
catch (JobExecutionAlreadyRunningException e) {
   e.printStackTrace();
}
catch (JobRestartException e) {
   e.printStackTrace();
}
catch (JobInstanceAlreadyCompleteException e) {
   e.printStackTrace();
}
catch (JobParametersInvalidException e) {
   e.printStackTrace();
}
    }
}

.....

其他的類就不在一一描述了.