springbatch入门练习(第二篇)

对第一遍内容的补充

<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns="http://www.springframework.org/schema/batch"
    xmlns:bean="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/batch
    http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <!-- 作业仓库 -->
    <job-repository id="jobRepository" data-source="dataSource"
        transaction-manager="transactionManager" isolation-level-for-create="SERIALIZABLE"
        table-prefix="BATCH_" max-varchar-length="1000"
    />

    <!-- 作业调度器 -->
    <bean:bean id="jobLauncher"
        class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <bean:property name="jobRepository" ref="jobRepository"/>
    </bean:bean>
    <!-- 配置大小为1的线程池 -->
    <task:executor id="executor" pool-size="1" />
    <!-- 异步作业调度器 -->
    <bean:bean id="jobLauncherAsyn"
        class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <bean:property name="jobRepository" ref="jobRepository"/>
        <!-- 为作业调度器配置执行的线程池,作业执行期间会从线程池中选择一个线程执行job -->
        <bean:property name="taskExecutor" ref="executor" />
    </bean:bean>
    <!-- 事务管理器 -->
    <bean:bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <bean:property name="dataSource" ref="dataSource" />
    </bean:bean>

    <!-- 数据源 -->
    <bean:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <bean:property name="driverClassName">
               <bean:value>com.mysql.jdbc.Driver</bean:value>
          </bean:property>
          <bean:property name="url">
               <bean:value>jdbc:mysql://127.0.0.1:3306/springbatch</bean:value>
          </bean:property>
          <bean:property name="username" value="root"></bean:property>
          <bean:property name="password" value="123456"></bean:property>
     </bean:bean>
</bean:beans>
<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns="http://www.springframework.org/schema/batch"
    xmlns:bean="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/batch
    http://www.springframework.org/schema/batch/spring-batch-2.2.xsd">
    <bean:import resource="classpath:job-context03.xml"/>
    <!-- 通过abstract属性定义baseJob为抽象的job,抽象的job不能被实例化 -->
    <job id="baseJob" abstract="true">
        <listeners>
            <listener ref="sysoutListener"></listener>
        </listeners>
    </job>
    <!-- billjob继承 baseJob,billjob拥有父类的所有特性,billjob执行的时候也会调用basejob中
                 定义的拦截器sysoutListener -->
    <!-- 定义一个批处理作业   restartable默认值是true支持重新启动,false不支持重新启动-->
    <job id="billJob" parent="baseJob" restartable="true">
        <!-- 定义个billStep的作业步,有一个面向批的操作组成 -->
        <step id="billStep">
            <!-- 定义批处理操作采用定义的事务管理器,负责批处理中事务管理操作 -->
            <tasklet transaction-manager="transactionManager">
                <!-- 定义了面向批的操作,定义了读操作csvItemReader,处理操作 creditBillProcessor,写操作csvItemWriter
                 commit-interval表示提交间隔的大小,即每处理两条数据进行一次写操作-->
                <chunk reader="csvItemReader" writer="csvItemWriter"
                    processor="creditBillProcessor" commit-interval="2">
                </chunk>
            </tasklet>
        </step>
        <!-- 定义拦截器 -->
        <!-- 如果父子中均定义了拦截器,通过设置merge属性为true对拦截器进行合并,如果为false,
                                                            则子类中的拦截器覆盖掉父类中的拦截器 -->
        <listeners merge="true">
            <listener ref="systemOutJobExecutionListener"></listener>
          <!--   <listener ref="sysoutListener"></listener>
            <listener ref="systemOutJobExecutionListener"></listener> -->
        </listeners>
        <!-- 定义参数校验 -->
        <validator ref="validator"></validator>
    </job>
    <!-- 执行该job的时候,必须输入date参数,最多输入date、name两个参数,任何其他参数的名字都会导致校验类不通过 -->
    <bean:bean id="validator"
        class="org.springframework.batch.core.job.DefaultJobParametersValidator">
        <bean:property name="requiredKeys">
            <bean:set>
                <bean:value>date</bean:value>
            </bean:set>
        </bean:property>
        <bean:property name="optionalKeys">
            <bean:set>
                <bean:value>inputResource</bean:value>
            </bean:set>
        </bean:property>
    </bean:bean>
    <bean:bean id="sysoutListener" class="com.batman.core.batch.listener.SystemOut">
    </bean:bean>
    <bean:bean id="systemOutJobExecutionListener" class="com.batman.core.batch.listener.SystemOutJobExecutionListener">
    </bean:bean>
    <!-- 读取信用卡账单文件,CSV格式 -->
    <!-- 通过设置scope="step"来定义 csvItemReader的生命周期与step绑定
                                通过使用step scope,可以设置属性的late binding(属性后绑定)能力-->
    <bean:bean id="csvItemReader"
        class="org.springframework.batch.item.file.FlatFileItemReader"
        scope="step">
        <!-- 读取文件资源 -->
        <bean:property name="resource"
            value="#{jobParameters[‘inputResource‘]}"/>
             <!--  value="classpath:credit-card-bill-201303.csv"/> -->
        <!-- 通过lineMapper可以把文本中的一行转换成领域对象CreditBill -->
        <bean:property name="lineMapper">
            <bean:bean
                class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
                <!-- 定义文本中的分割符号 -->
                <bean:property name="lineTokenizer" ref="lineTokenizer"/>
                <!-- 根据lineTokenizer中定义的names属性映射到creditBill中,最终组装成信用卡账单对象 -->
                <bean:property name="fieldSetMapper">
                    <bean:bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
                        <bean:property name="prototypeBeanName" value="creditBill">
                        </bean:property>
                    </bean:bean>
                </bean:property>
            </bean:bean>
        </bean:property>
    </bean:bean>
    <!-- lineTokenizer -->
    <bean:bean id="lineTokenizer"
        class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
        <bean:property name="delimiter" value=","/>
        <bean:property name="names">
            <bean:list>
                <bean:value>accountID</bean:value>
                <bean:value>name</bean:value>
                <bean:value>amount</bean:value>
                <bean:value>date</bean:value>
                <bean:value>address</bean:value>
            </bean:list>
        </bean:property>
    </bean:bean>

    <!-- 写信用卡账单文件,CSV格式 -->
    <bean:bean id="csvItemWriter"
        class="org.springframework.batch.item.file.FlatFileItemWriter"
        scope="step">
        <bean:property name="resource" value="file:target/outputFile.csv"/>
        <bean:property name="lineAggregator">
            <bean:bean
                class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
                <bean:property name="delimiter" value=","></bean:property>
                <bean:property name="fieldExtractor">
                    <bean:bean
                        class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
                        <bean:property name="names"
                             value="accountID,name,amount,date,address">
                        </bean:property>
                    </bean:bean>
                </bean:property>
            </bean:bean>
        </bean:property>
    </bean:bean>

    <bean:bean id="creditBill" scope="prototype"
        class="com.batman.core.batch.CreditBill">
    </bean:bean>
    <!-- 负责处理读入的数据 -->
    <bean:bean id="creditBillProcessor" scope="step"
        class="com.batman.core.batch.CreditBillProcessor">
    </bean:bean>
</bean:beans>
package com.batman.core.batch;

import java.util.Date;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class JobLaunch {
    /**
     * 执行批处理作业.<br>
     * @param jobPath    作业配置文件
     * @param jobName    作业名
     * @param builder    作业参数构造器
     */
    public static void executeJob(String jobPath, String jobName, JobParametersBuilder builder) {
        ApplicationContext context = new ClassPathXmlApplicationContext(jobPath);
        JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");
        Job job = (Job) context.getBean(jobName);
        try {
            JobExecution result = launcher.run(job, builder.toJobParameters());
            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //
    public static void executeJobAsyn(String jobPath, String jobName, JobParametersBuilder builder) {
        ApplicationContext context = new ClassPathXmlApplicationContext(jobPath);
        JobLauncher launcher = (JobLauncher) context.getBean("jobLauncherAsyn");
        Job job = (Job) context.getBean(jobName);
        try {
            JobExecution result = launcher.run(job, builder.toJobParameters());
            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        /*executeJob("job.xml", "billJob",
                new JobParametersBuilder().addString("date", "20130308"));*/
        /*executeJob("job.xml", "billJob",
                new JobParametersBuilder().addDate("date", new Date())
                .addString("name", "aad")
                .addString("inputResource", "classpath:credit-card-bill-201303.csv"));*/
        /*-------异步执行--------*/
        executeJobAsyn("job.xml", "billJob",
                new JobParametersBuilder().addDate("date", new Date())
                .addString("inputResource", "classpath:credit-card-bill-201303.csv"));
    }
    /*public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "job.xml");
        //获取作业调度器
        JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");
        //获取任务对象
        Job job = (Job) context.getBean("billJob");
        try {
            //通过JobLauncher的run方法执行billJob任务
            JobExecution result = launcher.run(job, new JobParameters());
            System.out.println(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

}

原文地址:https://www.cnblogs.com/mutong1228/p/9053849.html

时间: 2024-08-09 20:10:41

springbatch入门练习(第二篇)的相关文章

Python学习笔记之入门(第二篇)

1.第一个Python代码 在Linux下/home/zx 目录下新建hello.py文件 1 #vim hello.py //添加如下内容 2 3 #!/usr/bin/env python 4 5 # -*- coding:utf-8 -*- 6 print "Hello,World" 7 8 #chmod +x hello.py //添加执行权限 执行代码: ./hello.py 结果: python内部执行过程如下:   python首先把hello.py文件读到内存当中,然后

Linux从入门到放弃、零基础入门Linux(第二篇):在虚拟机vmware中安装linux(一)超详细,分步图解

一.Vmware vmware介绍:VMware,Inc. (Virtual Machine ware)是一个“虚拟PC”软件公司,提供服务器.桌面虚拟化的解决方案.其虚拟化平台的产品包括播放器:它能使个人用台式电脑运行虚拟机器,融合器,它是用户基于英特尔结构苹果机的桌面虚拟化产品,工作站的软件开发商和企业的资讯科技专才,能使虚拟分区的服务器,ESX服务器(一种能直接在硬件上运行的企业级的虚拟平台),虚拟的SMP让一个虚拟机同时使用四个物理处理器,和VMFS使多个ESX服务器分享块存储器. vm

Vue入门教程 第二篇 (数据绑定与响应式)

数据绑定 Vue.js 的核心是一个允许采用简洁的模板语法来声明式地将数据渲染进 DOM 的系统: 1 <div id="app"> 2 {{ message }} 3 </div> 1 var app = new Vue({ 2 el: '#app', 3 data: { 4 message: 'Hello Vue!' 5 } 6 }) 执行结果:Hello Vue! 除了上面的绑定方式,还有另外一种: 1 <div id="app"

spring入门学习第二篇

依赖注入IOC IOC:inverse of control:控制反转 2004年,Martin Fowler探讨了同一个问题,既然IOC是控制反转,那么到底是“哪些方面的控制被反转了呢?”,经过详细地分析和论证后,他得出了答案:“获得依赖对象的过程被反转了”.控制被反转之后,获得依赖对象的过程由自身管理变为了由IOC容器主动注入.于是,他给“控制反转”取了一个更合适的名字叫做“依赖注入(Dependency Injection)”.他的这个答案,实际上给出了实现IOC的方法:注入.所谓依赖注入

【第二篇】ASP.NET MVC快速入门之数据注解(MVC5+EF6)

目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策略(MVC5+EF6) [第四篇]ASP.NET MVC快速入门之完整示例(MVC5+EF6) [番外篇]ASP.NET MVC快速入门之免费jQuery控件库(MVC5+EF6) 请关注三石的博客:http://cnblogs.com/sanshi 数据库连接字符串 上一篇文章中,我们使用MVC的

【OpenCV入门指南】第二篇 缩放图像

[OpenCV入门指南]第二篇 缩放图像 上一篇<[OpenCV入门指南]第一篇安装OpenCV>讲解了如何在VS2008下安装和配置OpenCV,本篇将介绍使用OpenCV来缩放图片.首先介绍几个关键函数--cvResize和cvCreateImage <OpenCV入门指南>系列文章地址:http://blog.csdn.net/morewindows/article/category/1291764 一. 主要函数介绍 1.1 cvResize 函数功能:图像大小变换 函数原

ElasticSearch入门 第六篇:复合数据类型——数组,对象和嵌套

这是ElasticSearch 2.4 版本系列的第六篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 ElasticSearch入门 第三篇:索引 ElasticSearch入门 第四篇:使用C#添加和更新文档 ElasticSearch入门 第五篇:使用C#查询文档 ElasticSearch入门 第六篇:复合数据类型——数组,对象和嵌套 在ElasticSearch中,使用JSON结构来存储数据,

Qt入门之基础篇 ( 二 ) :Qt项目建立、编译、运行和发布过程解析

转载请注明出处:CN_Simo. 题解: 本篇内容主讲Qt应用从创建到发布的整个过程,旨在帮助读者能够快速走进Qt的世界. 本来计划是讲解Qt源码静态编译,如此的话读者可能并不能清楚地知道为何要静态编译,所以借此篇内容说明一下原由并为之后文章的学习做准备. 即使本片内容只是在围绕一个小小的HelloWorld程序开展,但还是希望朋友们不要急于求成,"欲速则不达". 文章整体思路: 我们循序渐进地来看,一个Qt应用的完成有以下一个重要的步骤: 项目创建->源码编译->程序运行

Python之路【第二篇】:Python基础(一)

Python之路[第二篇]:Python基础(一) 入门知识拾遗 一.作用域 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. 1 2 3 if 1==1:     name = 'wupeiqi' print  name 下面的结论对吗? 外层变量,可以被内层变量使用 内层变量,无法被外层变量使用 二.三元运算 1 result = 值1 if 条件 else 值2 如果条件为真:result = 值1如果条件为假:result = 值2 三.进制 二进制,01 八进

ElasticSearch入门 第八篇:存储

这是ElasticSearch 2.4 版本系列的第八篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 ElasticSearch入门 第三篇:索引 ElasticSearch入门 第四篇:使用C#添加和更新文档 ElasticSearch入门 第五篇:使用C#查询文档 ElasticSearch入门 第六篇:复合数据类型——数组,对象和嵌套 ElasticSearch入门 第七篇:分析器 Elasti