spring bacth

從頭認識SpringBatch批處理框架--實例場景一信用卡消費對帳

場景說明html

我的使用信用卡消費,銀行按期發送銀行卡消費帳單,本例將模擬銀行處理我的信用卡消費對帳單對帳,銀行須要按期地把我的消費的記錄導出成csv文件,而後交給對帳系統處理。java

主要流程spring

(從credit-card-bill-201303.csv)讀取數據---->處理數據----->寫數據到 outputFile文件數據庫

項目結構app

項目結構說明:框架

 

  • CreditBill:信用卡消費記錄領域對象
  • CreditBillProcessor:信用卡消費記錄處理類
  • jobLaunch:調用批處理做業類
  • jobLaunchTest:Junit單元測試,使用Spring提供的測試框架
  • credit-card-bill-201303.csv:信用卡消費帳單文件
  • job-context.xml:定義做業基礎信息
  • job.xml:定義做業文件
  • outputFile.xml:輸出處理事後的信用卡消費帳單文件
項目實現步驟詳解:
1.準備credit-card-bill-201303.csv對帳文件
這裏咱們使用csv格式的文件,該文件的每一行表示信用卡消費記錄,中間用逗號分隔,分別表示:
銀行卡帳戶、帳戶名、消費金額、消費日期、消費場所以下圖所示:
 
2.定義領域對象:
爲了與帳單文件造成映射,須要新建信用卡消費記錄對象 -CreditBill,主要屬性:銀行卡帳戶、帳戶名、消費金額、消費日期、消費場所
具體代碼以下:
[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. package com.my.domain;  
  2. /** 
  3.  * 信用卡消費記錄領域對象 
  4.  * 該類主要用於在ItemReader讀取文件數據以後轉換成領域對象CreditBill, 
  5.  * 以便於ItemProcessoe和ItemWriter操做使用 
  6.  * @author wbw 
  7.  * 
  8.  */  
  9. public class CreditBill {  
  10.     /** 
  11.      * 銀行帳戶 
  12.      */  
  13.     private String accountID;  
  14.     /** 
  15.      * 帳戶名 
  16.      */  
  17.     private String name;  
  18.     /** 
  19.      * 消費金額 
  20.      */  
  21.     private double amount;  
  22.     /** 
  23.      * 消費日期 
  24.      */  
  25.     private String date;  
  26.     /** 
  27.      * 消費場所 
  28.      */  
  29.     private String address;  
  30.     /** 
  31.      * @return the 銀行帳戶 
  32.      */  
  33.     public String getAccountID() {  
  34.         return accountID;  
  35.     }  
  36.     /** 
  37.      * @param 銀行帳戶 the accountID to set 
  38.      */  
  39.     public void setAccountID(String accountID) {  
  40.         this.accountID = accountID;  
  41.     }  
  42.     /** 
  43.      * @return the 帳戶名 
  44.      */  
  45.     public String getName() {  
  46.         return name;  
  47.     }  
  48.     /** 
  49.      * @param 帳戶名 the name to set 
  50.      */  
  51.     public void setName(String name) {  
  52.         this.name = name;  
  53.     }  
  54.     /** 
  55.      * @return the 消費金額 
  56.      */  
  57.     public double getAmount() {  
  58.         return amount;  
  59.     }  
  60.     /** 
  61.      * @param 消費金額 the amount to set 
  62.      */  
  63.     public void setAmount(double amount) {  
  64.         this.amount = amount;  
  65.     }  
  66.     /** 
  67.      * @return the 消費日期 
  68.      */  
  69.     public String getDate() {  
  70.         return date;  
  71.     }  
  72.     /** 
  73.      * @param 消費日期 the date to set 
  74.      */  
  75.     public void setDate(String date) {  
  76.         this.date = date;  
  77.     }  
  78.     /** 
  79.      * @return the 消費場所 
  80.      */  
  81.     public String getAddress() {  
  82.         return address;  
  83.     }  
  84.     /** 
  85.      * @param 消費場所 the address to set 
  86.      */  
  87.     public void setAddress(String address) {  
  88.         this.address = address;  
  89.     }  
  90.   
  91.       
  92. }  
3.定義job-context.xml批處理基礎信息
該配置文件主要是配置做業倉庫、做業調度器、事務管理器,具體代碼以下:
[html]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"      
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:p="http://www.springframework.org/schema/p"      
  5.     xmlns:tx="http://www.springframework.org/schema/tx"   
  6.     xmlns:aop="http://www.springframework.org/schema/aop"      
  7.     xmlns:context="http://www.springframework.org/schema/context"      
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  9.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  10.     http://www.springframework.org/schema/tx    
  11.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
  12.     http://www.springframework.org/schema/aop    
  13.     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
  14.     http://www.springframework.org/schema/context    
  15.     http://www.springframework.org/schema/context/spring-context-2.5.xsd"      
  16.     default-autowire="byName">  
  17.     <!--定義做業倉庫SpringBatch提供了兩種做業倉庫來記錄job執行期產生的信息:一種是內存,另外一種是數據庫    -->  
  18.     <bean id="jobRepository"   
  19.         class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">  
  20.     </bean>  
  21.     <!--定義做業調度器,用來啓動Job -->  
  22.     <bean id="jobLauncher"   
  23.         class="org.springframework.batch.core.launch.support.SimpleJobLauncher">  
  24.         <property name="jobRepository" ref="jobRepository"/>  
  25.     </bean>  
  26.     <!--事務管理器,用於springbatch框架在對數據操做過程當中體統事務能力-->  
  27.     <bean id="transactionManager"   
  28.         class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>  
  29. </beans>  
4.定義job.xml文件
job.xml文件主要配置批處理做業Job、Step、ItemReader(讀數據)、ItemProcessoe(處理數據)、 ItemWriter(寫數據) 具體的配置以下圖:
[html]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <bean:beans xmlns="http://www.springframework.org/schema/batch"      
  3.     xmlns:bean="http://www.springframework.org/schema/beans"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      
  5.     xmlns:p="http://www.springframework.org/schema/p"   
  6.     xmlns:tx="http://www.springframework.org/schema/tx"      
  7.     xmlns:aop="http://www.springframework.org/schema/aop"   
  8.     xmlns:context="http://www.springframework.org/schema/context"      
  9.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  10.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  11.     http://www.springframework.org/schema/tx   
  12.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
  13.     http://www.springframework.org/schema/aop   
  14.     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
  15.     http://www.springframework.org/schema/context   
  16.     http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  17.     http://www.springframework.org/schema/batch   
  18.     http://www.springframework.org/schema/batch/spring-batch-2.2.xsd">  
  19.     <!--引入job-context.xml配置文件-->  
  20.     <bean:import resource="classpath:job-context.xml"/>  
  21.     <!--定義billJob billStep 包含讀數據  處理數據 寫數據-->  
  22.     <job id="billJob">  
  23.         <step id="billStep">  
  24.             <tasklet transaction-manager="transactionManager">  
  25.                 <!--commit-interval="2" 表示任務提交間隔的大小 此處表示每處理2條數據 進行一次寫入操做-->  
  26.                 <chunk reader="csvItemReader" writer="csvItemWriter"   
  27.                     processor="creditBillProcessor" commit-interval="2">  
  28.                 </chunk>  
  29.             </tasklet>  
  30.         </step>  
  31.     </job>  
  32.     <!-- 讀取信用卡帳單文件,CSV格式 -->  
  33.     <bean:bean id="csvItemReader"  
  34.         class="org.springframework.batch.item.file.FlatFileItemReader"   
  35.         scope="step">  
  36.         <!--設置讀取的文件資源-->  
  37.         <bean:property name="resource"   
  38.             value="classpath:credit-card-bill-201303.csv"/>  
  39.          <!--將文本中的每行記錄轉換爲領域對象-->  
  40.         <bean:property name="lineMapper">  
  41.             <bean:bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">  
  42.                <!--引用lineTokenizer-->  
  43.                <bean:property name="lineTokenizer" ref="lineTokenizer"/>  
  44.                 <!--fieldSetMapper根據lineTokenizer中定義的names屬性映射到領域對象中去-->  
  45.                 <bean:property name="fieldSetMapper">  
  46.                     <bean:bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">  
  47.                         <bean:property name="prototypeBeanName" value="creditBill">  
  48.                         </bean:property>  
  49.                     </bean:bean>  
  50.                 </bean:property>  
  51.             </bean:bean>  
  52.         </bean:property>  
  53.     </bean:bean>  
  54.     <!-- lineTokenizer 定義文本中每行的分隔符號 以及每行映射成FieldSet對象後的name列表 -->  
  55.     <bean:bean id="lineTokenizer"   
  56.         class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">  
  57.         <bean:property name="delimiter" value=","/>  
  58.         <bean:property name="names">  
  59.             <bean:list>  
  60.                 <bean:value>accountID</bean:value>  
  61.                 <bean:value>name</bean:value>  
  62.                 <bean:value>amount</bean:value>  
  63.                 <bean:value>date</bean:value>  
  64.                 <bean:value>address</bean:value>  
  65.             </bean:list>  
  66.         </bean:property>  
  67.     </bean:bean>  
  68.       
  69.     <!-- 寫信用卡帳單文件,CSV格式 -->  
  70.     <bean:bean id="csvItemWriter"   
  71.         class="org.springframework.batch.item.file.FlatFileItemWriter"   
  72.         scope="step">  
  73.         <bean:property name="resource" value="file:outputFile.csv"/>  
  74.         <bean:property name="lineAggregator">  
  75.             <bean:bean   
  76.                 class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">  
  77.                 <bean:property name="delimiter" value=","></bean:property>  
  78.                 <bean:property name="fieldExtractor">  
  79.                     <bean:bean   
  80.                         class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">  
  81.                         <bean:property name="names" value="accountID,name,amount,date,address">  
  82.                         </bean:property>  
  83.                     </bean:bean>  
  84.                 </bean:property>  
  85.             </bean:bean>  
  86.         </bean:property>  
  87.     </bean:bean>  
  88.     <!--領域對象 並標註爲原型-->  
  89.     <bean:bean id="creditBill" scope="prototype"  
  90.         class="com.my.domain.CreditBill">  
  91.     </bean:bean>  
  92.     <!--負責業務數據的處理-->  
  93.     <bean:bean id="creditBillProcessor" scope="step"  
  94.         class="com.my.processor.CreditBillProcessor">  
  95.     </bean:bean>  
  96. </bean:beans>  
5.建立ItemProcessor
該類主要是用於處理ItemReader讀取的數據,一般包括數據過濾、數據轉換等操做,此處咱們只是簡單的打印帳單信息。具體代碼以下:
[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. /** 
  2.  *  
  3.  */  
  4. package com.my.processor;  
  5.   
  6. import org.springframework.batch.item.ItemProcessor;  
  7.   
  8. import com.my.domain.CreditBill;  
  9.   
  10. /** 
  11.  * 處理數據器 
  12.  * @author wbw 
  13.  * 
  14.  */  
  15. public class CreditBillProcessor implements ItemProcessor<CreditBill, CreditBill> {  
  16.   
  17.     public CreditBill process(CreditBill bill) throws Exception {  
  18.         System.out.println("信用卡消費領域對象:"+bill.getAccountID()+"-"+bill.getName()+"-"+bill.getAmount()+"-"+bill.getAddress());  
  19.         return bill;  
  20.     }  
  21. }  
6.啓動Job
咱們這裏介紹兩種啓動運行方式,
第一種:main方法
[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. /** 
  2.  *  
  3.  */  
  4. package com.my.batch;  
  5.   
  6. import org.springframework.batch.core.Job;  
  7. import org.springframework.batch.core.JobExecution;  
  8. import org.springframework.batch.core.JobParameters;  
  9. import org.springframework.batch.core.launch.JobLauncher;  
  10. import org.springframework.context.ApplicationContext;  
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  12.   
  13. /** 
  14.  * 測試 
  15.  * @author wbw 
  16.  * 
  17.  */  
  18. public class JobLaunch {  
  19.       
  20.     /** 
  21.      * @param args 
  22.      */  
  23.     @SuppressWarnings("resource")  
  24.     public static void main(String[] args) {  
  25.         //初始化應用上下文  
  26.         ApplicationContext context = new ClassPathXmlApplicationContext("job.xml");  
  27.         //獲取做業調度,根據Bean的名稱從Spring的上下文獲取  
  28.         JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");  
  29.         //獲取任務對象  
  30.         Job job = (Job) context.getBean("billJob");  
  31.         try {  
  32.             JobExecution result = launcher.run(job, new JobParameters());  
  33.             System.out.println(result.toString());  
  34.         } catch (Exception e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.     }  
  38. }  
第二種:Junit單元測試

[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. package com.my.batch;  
  2.   
  3.   
  4. import org.junit.After;  
  5. import org.junit.Before;  
  6. import org.junit.Test;  
  7. import org.junit.runner.RunWith;  
  8. import org.springframework.batch.core.Job;  
  9. import org.springframework.batch.core.JobExecution;  
  10. import org.springframework.batch.core.JobParameters;  
  11. import org.springframework.batch.core.launch.JobLauncher;  
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.beans.factory.annotation.Qualifier;  
  14.   
  15. @RunWith(SpringJUnit4ClassRunner.class)  
  16. @ContextConfiguration(locations={"job.xml"})  
  17. public class JobLaunchTest {  
  18.     @Autowired  
  19.     private JobLauncher jobLauncher;  
  20.       
  21.     @Autowired@Qualifier("billJob")  
  22.     private Job job;  
  23.   
  24.     @Before  
  25.     public void setUp() throws Exception {  
  26.     }  
  27.   
  28.     @After  
  29.     public void tearDown() throws Exception {  
  30.     }  
  31.       
  32.     @Test  
  33.     public void billJob() throws Exception {  
  34.         JobExecution result = jobLauncher.run(job, new JobParameters());            
  35.         System.out.println(result.toString());       
  36.     }  
  37. }  
執行Job後 outputFile文件已錄入數據


控制檯信息:
這裏只顯示了兩條信用卡消費帳單信息,由於咱們在job.xml文件中設置任務提交間隔的大小 每處理2條數據 進行一次寫入操做。以下圖
 
總結:
從這個實例場景中,咱們學會了使用SpringBatch已經提供好的功能組件和基礎設施,快速搭建批處理應用。瞭解了SpringBatch的一些基本概念:
JobRepository:做業倉庫,負責Job、Step執行過程當中的狀態保存;
JobLauncher:做業調度器,提供執行Job的入口;
Job:做業,由一個或多個的Step組成;
Step:做業步,Job的一個執行環節,由一個或多個的Step組成Job
Tasklet:Stp中具體執行邏輯的操做,能夠重複執行,能夠設置具體的同步、異步操做
Chunk:給定數量的Item集合
Item:一條數據記錄
ItenReader:從數據源(文件、數據庫或消息隊列等)中獲取Item
ItemProcessor:在Item寫數據以前,對數據進行數據過濾、數據清洗、數據轉換、數據校驗等操做
ItemWriter:將Item數據記錄批量寫入數據源(文件、數據庫或消息隊列等)
相關文章
相關標籤/搜索