Spring Batch是一个基于Spring的企业级批处理框架,它通过配合定时器Quartz来轻易实现大批量的数据读取或插入,并且全程自动化,无需人员管理。

在使用spring batch之前,得对spring batch的流程有一个基本了解

每个batch它都包含了一个job,而一个job中却有可能包含多个step,整个batch中干活的是step,batch主要是用来对数据的操作,所以step就有三个操作数据的东西,一个是ItemReader用来读取数据的,一个是ItemProcessor用来处理数据的,一个是ItemWriter用来写数据(可以是文件也可以是插入sql语句),JobLauncher用来启动Job,JobRepository是上述处理提供的一种持久化机制,它为JobLauncher,Job,和Step实例提供CRUD操作。

pom.xml  三个batch的jar包

  1. <span style="white-space:pre;">     </span><dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-batch-core</artifactId>
  4. <version>2.1.8.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework</groupId>
  8. <artifactId>spring-batch-infrastructure</artifactId>
  9. <version>2.1.8.RELEASE</version>
  10. <span style="white-space:pre;"> </span></dependency>
  11. <dependency>
  12. <groupId>org.springframework</groupId>
  13. <artifactId>spring-batch-test</artifactId>
  14. <version>2.1.8.RELEASE</version>
  15. </dependency>

batch.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:batch="http://www.springframework.org/schema/batch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://www.springframework.org/schema/batch
  4. http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
  5. http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  7. ">
  8. <bean id="jobLauncher"
  9. class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
  10. <property name="jobRepository" ref="jobRepository" />
  11. </bean>
  12. <bean id="jobRepository"
  13. class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
  14. <property name="validateTransactionState" value="false" />
  15. </bean>
  16. <span style="white-space:pre;">     </span><!--一个job-->
  17. <batch:job id="writerteacherInterview">
  18. <batch:step id="teacherInterview">
  19. <batch:tasklet>
  20. <batch:chunk reader="jdbcItemReaderTeacherInterview" writer="teacherInterviewItemWriter"
  21. processor="teacherInterviewProcessor" commit-interval="10">
  22. </batch:chunk>
  23. </batch:tasklet>
  24. </batch:step>
  25. </batch:job>
  26. <!--job的读取数据操作-->
  27. <bean id="jdbcItemReaderTeacherInterview"
  28. class="org.springframework.batch.item.database.JdbcCursorItemReader"
  29. scope="step">
  30. <property name="dataSource" ref="dataSource" />
  31. <property name="sql"
  32. value="select distinct teacherName ,count(teacherName) as num from examininterviewrecord   where pdate >'${detail_startime}' and pdate < '${detail_endtime}'  GROUP BY teacherName " />
  33. <property name="rowMapper" ref="teacherInterviewMapper">
  34. </property>
  35. </bean>
  36. </beans>

读取数据    teacherInterviewMapper

  1. package com.yc.batch;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import org.springframework.jdbc.core.RowMapper;
  5. import org.springframework.stereotype.Component;
  6. import com.yc.vo.TeacherInterviewdetail;
  7. import com.yc.vo.TeacherWorkdetail;
  8. import com.yc.vo.Workdetail;
  9. @Component("teacherInterviewMapper")
  10. public class TeacherInterviewMapper implements RowMapper {
  11. @Override
  12. public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
  13. TeacherInterviewdetail TId=new TeacherInterviewdetail();
  14. TId.setTeacherName(rs.getString("teacherName"));
  15. TId.setNum(rs.getInt("num"));
  16. return TId;
  17. }
  18. }

处理数据  teacherInterviewProcessor ,这个处理数据方法,一般都是在这里在这里进行一些数据的加工,比如有些数据没有读到,你也可以在这个方法和后面那个写入数据的类里面写,所以就导致了这个类里面你可以什么都不敢,直接把数据抛到后面去,让后面的写数据类来处理;我这里就是处理数据的这个类什么都没写,但是最好还是按它的规则来!

  1. package com.yc.batch;
  2. import org.hibernate.engine.transaction.jta.platform.internal.SynchronizationRegistryBasedSynchronizationStrategy;
  3. import org.springframework.batch.item.ItemProcessor;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.stereotype.Service;
  6. import com.yc.vo.TeacherInterviewdetail;
  7. import com.yc.vo.TeacherWorkdetail;
  8. import com.yc.vo.Workdetail;
  9. //业务层
  10. @Component("teacherInterviewProcessor")
  11. public class TeacherInterviewProcessor implements ItemProcessor<TeacherInterviewdetail, TeacherInterviewdetail> {
  12. @Override
  13. public TeacherInterviewdetail process(TeacherInterviewdetail teacherInterviewdetail) throws Exception {
  14. return teacherInterviewdetail;
  15. }
  16. }

写数据 teacherInterviewItemWriter 这个类里面主要是把数据写进一个文件里,同时我这个类里面还有一些数据处理

  1. package com.yc.batch;
  2. import java.io.InputStream;
  3. import java.text.NumberFormat;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Properties;
  7. import javax.annotation.Resource;
  8. import org.springframework.batch.item.ItemWriter;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.stereotype.Service;
  11. import com.yc.biz.ExamineeClassBiz;
  12. import com.yc.biz.WorkBiz;
  13. import com.yc.utils.CsvUtils;
  14. import com.yc.vo.TeacherInterviewdetail;
  15. import com.yc.vo.TeacherWorkdetail;
  16. import com.yc.vo.Workdetail;
  17. import net.sf.ehcache.util.PropertyUtil;
  18. //写
  19. @Component("teacherInterviewItemWriter")
  20. public class TeacherInterviewItemWriter implements ItemWriter<TeacherInterviewdetail>{
  21. @Override
  22. public void write(List<? extends TeacherInterviewdetail> teacherInterviewdetails) throws Exception {
  23. Properties props = new Properties();
  24. InputStream in= PropertyUtil.class.getClassLoader().getResourceAsStream("connectionConfig.properties");
  25. props.load(in);
  26. String time=props.getProperty("detail_time");
  27. CsvUtils cu=new CsvUtils();
  28. List<Object> works=new ArrayList<Object>();
  29. for(TeacherInterviewdetail t:teacherInterviewdetails){
  30. works.add(t);
  31. }
  32. String path=this.getClass().getResource("/").getPath();
  33. path=path.substring(0,path.lastIndexOf("/"));
  34. path=path.substring(0,path.lastIndexOf("/"));
  35. path=path.substring(0,path.lastIndexOf("/"));
  36. path=path.substring(0,path.lastIndexOf("/"));
  37. cu.writeCsv(path+"/csv/teacherInterview_"+time+".csv",works );
  38. }
  39. }

我这里有用到一个吧数据写进CSV文件的jar包

  1. <span style="white-space:pre;">         </span><dependency>
  2. <groupId>net.sourceforge.javacsv</groupId>
  3. <artifactId>javacsv</artifactId>
  4. <version>2.0</version>
  5. </dependency>

CsvUtils帮助类的写入CSV文件方法

  1. /**
  2. * 写入CSV文件
  3. * @throws IOException
  4. */
  5. public void writeCsv(String path,List<Object> t) throws IOException{
  6. String csvFilePath = path;
  7. String filepath=path.substring(0,path.lastIndexOf("/"));
  8. File f=new File(filepath);
  9. if(!f.exists()){
  10. f.mkdirs();
  11. }
  12. File file=new File(path);
  13. if(!file.exists()){
  14. file.createNewFile();
  15. }
  16. CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("GBK"));
  17. try {
  18. for(Object obj:t){
  19. String[] contents=obj.toString().split(",");
  20. wr.writeRecord(contents);
  21. }
  22. wr.close();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }

就这样一个基本的batch流程就跑起来了,它通过从数据里读取一些数据,然后经过处理后,被存进服务器下的一个文件里面,之后像这种数据的读取就不需要去数据库里面

查询了,而是可以直接通过读取CSV文件来处理这个业务。一般使用这个的都会配一个定时器,让它们每隔一段时间跑一次,从而获得较新的数据

下面是定时器的配置

定时器的配置非常简单,我是使用注解方式来配置的

定时器任务类

  1. package com.yc.task.impl;
  2. import javax.transaction.Transactional;
  3. import org.springframework.batch.core.JobParametersInvalidException;
  4. import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
  5. import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
  6. import org.springframework.batch.core.repository.JobRestartException;
  7. import org.springframework.batch.item.ItemProcessor;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.scheduling.annotation.Scheduled;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.stereotype.Service;
  12. import com.yc.batch.ClassBatch;
  13. import com.yc.batch.MessageItemBatch;
  14. import com.yc.batch.TeacherInterviewBatch;
  15. import com.yc.batch.TearcherBatch;
  16. import com.yc.po.Work;
  17. import com.yc.task.WorkTask;
  18. import com.yc.vo.Workdetail;
  19. @Service
  20. public class WorkTaskImpl implements WorkTask{
  21. @Autowired
  22. private TeacherInterviewBatch teacherInterviewBatch;//教师访谈记录
  23. public void setTeacherInterviewBatch(TeacherInterviewBatch teacherInterviewBatch) {
  24. this.teacherInterviewBatch = teacherInterviewBatch;
  25. }
  26. @Scheduled(cron= "0 30 22 * * ?")   //每天晚上十点30执行一次  这个注解会让框架会自动把这个方法看成任务启动方法
  27. @Override
  28. public void task() {
  29. try {
  30. teacherInterviewBatch.test();//教师访谈
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }

定时器所真正要执行的方法

  1. package com.yc.batch;
  2. import javax.annotation.Resource;
  3. import org.apache.commons.jexl2.Main;
  4. import org.springframework.batch.core.Job;
  5. import org.springframework.batch.core.JobExecution;
  6. import org.springframework.batch.core.JobParameters;
  7. import org.springframework.batch.core.JobParametersBuilder;
  8. import org.springframework.batch.core.JobParametersInvalidException;
  9. import org.springframework.batch.core.launch.JobLauncher;
  10. import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
  11. import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
  12. import org.springframework.batch.core.repository.JobRestartException;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.stereotype.Component;
  15. @Component
  16. public class TeacherInterviewBatch {
  17. private Job job;
  18. private JobLauncher launcher;
  19. @Resource(name="writerteacherInterview")
  20. public void setJob(Job job) {
  21. this.job = job;
  22. }
  23. @Autowired
  24. public void setLauncher(JobLauncher launcher) {
  25. this.launcher = launcher;
  26. }
  27. public void test() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException{
  28. JobParameters jobParameters =
  29. new JobParametersBuilder()
  30. .addLong("time",System.currentTimeMillis()).toJobParameters();
  31. JobExecution result = launcher.run(job, jobParameters);
  32. }
  33. }

就这样batch就被定时器调度起来了,每天十点准时使用batch来操作数据

转自:https://blog.csdn.net/pttaoge/article/details/76684656

spring batch的使用和定时器Quart的使用的更多相关文章

  1. Spring Batch在大型企业中的最佳实践

    在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后进行一系列的后续处理.这样的过程就是" ...

  2. spring batch资料收集

    spring batch官网 Spring Batch在大型企业中的最佳实践 一篇文章全面解析大数据批处理框架Spring Batch Spring Batch系列总括

  3. Spring Batch学习笔记三:JobRepository

    此系列博客皆为学习Spring Batch时的一些笔记: Spring Batch Job在运行时有很多元数据,这些元数据一般会被保存在内存或者数据库中,由于Spring Batch在默认配置是使用H ...

  4. Spring Batch学习笔记二

    此系列博客皆为学习Spring Batch时的一些笔记: Spring Batch的架构 一个Batch Job是指一系列有序的Step的集合,它们作为预定义流程的一部分而被执行: Step代表一个自 ...

  5. 初探Spring Batch

    此系列博客皆为学习Spring Batch时的一些笔记: 为什么我们需要批处理? 我们不会总是想要立即得到需要的信息,批处理允许我们在请求处理之前就一个既定的流程开始搜集信息:比如说一个银行对账单,我 ...

  6. Spring Batch 中文参考文档 V3.0.6 - 1 Spring Batch介绍

    1 Spring Batch介绍 企业领域中许多应用系统需要采用批处理的方式在特定环境中运行业务操作任务.这种业务作业包括自动化,大量信息的复杂操作,他们不需要人工干预,并能高效运行.这些典型作业包括 ...

  7. Spring Batch 批处理框架

    <Spring Batch 批处理框架>基本信息作者: 刘相 出版社:电子工业出版社ISBN:9787121252419上架时间:2015-1-24出版日期:2015 年2月开本:16开页 ...

  8. [Spring Batch] 图解Spring Batch原理

    找到一副以前学习的图,稻清楚的描述了Spring Batch运行原理:  

  9. Spring Batch实践

    Spring Batch在大型企业中的最佳实践 在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后 ...

随机推荐

  1. backpropagation算法示例

    backpropagation算法示例 下面举个例子,假设在某个mini-batch的有样本X和标签Y,其中\(X\in R^{m\times 2}, Y\in R^{m\times 1}\),现在有 ...

  2. centos 7 配置ip

    1.动态获取ip(前提是你的路由器已经开启了DHCP) 修改网卡配置文件 vi /etc/sysconfig/network-scripts/ifcfg-ens32    (最后一个为网卡名称) 动态 ...

  3. 菜鸟之路——机器学习之KNN算法个人理解及Python实现

    KNN(K Nearest Neighbor) 还是先记几个关键公式 距离:一般用Euclidean distance   E(x,y)√∑(xi-yi)2 .名字这么高大上,就是初中学的两点间的距离 ...

  4. [转]核函数K(kernel function)

    1 核函数K(kernel function)定义 核函数K(kernel function)就是指K(x, y) = <f(x), f(y)>,其中x和y是n维的输入值,f(·) 是从n ...

  5. POJ 2217:Secretary(后缀数组)

    题目大意:求两个字符串的公共子串. 分析: 模板题,将两个字符串接起来用不会出现的字符分割,然后求分属两个字符串的相邻后缀lcp的最大值即可. 代码: program work; type arr=. ...

  6. 【bzoj3028】食物 数论+生成函数

    题目描述 明明这次又要出去旅游了,和上次不同的是,他这次要去宇宙探险! 我们暂且不讨论他有多么NC,他又幻想了他应该带一些什么东西.理所当然的,你当然要帮他计算携带N件物品的方案数. 他这次又准备带一 ...

  7. linux系统——hosts文件修改

    1. 关于/etc/host,主机名和IP配置文件 Hosts - The static table lookup for host name(主机名查询静态表) Linux 的/etc/hosts是 ...

  8. CDOJ 1256 二维前缀和处理

    昊昊喜欢运动 他NN 天内会参加MM 种运动(每种运动用一个[1,m][1,m] 的整数表示) 舍友有QQ 个问题 问昊昊第ll 天到第rr 天参加了多少种不同的运动 Input 输入两个数NN , ...

  9. 网页内容切换效果实现的15个jQuery插件

    原文发布时间为:2010-02-01 -- 来源于本人的百度文章 [由搬家工具导入] http://www.webjx.com/javascript/jsajax-15550.html

  10. linux 源代码目录结构

    Linux源代码目录树结构 (2008-04-21 09:14) 分类: Linux/Unix Linux用来支持各种体系结构的源代码包含大约4500个C语言程序,存放在270个左右的子目录下,总共大 ...