spring batch的使用和定时器Quart的使用
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包
- <span style="white-space:pre;"> </span><dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-batch-core</artifactId>
- <version>2.1.8.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-batch-infrastructure</artifactId>
- <version>2.1.8.RELEASE</version>
- <span style="white-space:pre;"> </span></dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-batch-test</artifactId>
- <version>2.1.8.RELEASE</version>
- </dependency>
batch.xml
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:batch="http://www.springframework.org/schema/batch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/batch
- http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
- ">
- <bean id="jobLauncher"
- class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
- <property name="jobRepository" ref="jobRepository" />
- </bean>
- <bean id="jobRepository"
- class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
- <property name="validateTransactionState" value="false" />
- </bean>
- <span style="white-space:pre;"> </span><!--一个job-->
- <batch:job id="writerteacherInterview">
- <batch:step id="teacherInterview">
- <batch:tasklet>
- <batch:chunk reader="jdbcItemReaderTeacherInterview" writer="teacherInterviewItemWriter"
- processor="teacherInterviewProcessor" commit-interval="10">
- </batch:chunk>
- </batch:tasklet>
- </batch:step>
- </batch:job>
- <!--job的读取数据操作-->
- <bean id="jdbcItemReaderTeacherInterview"
- class="org.springframework.batch.item.database.JdbcCursorItemReader"
- scope="step">
- <property name="dataSource" ref="dataSource" />
- <property name="sql"
- value="select distinct teacherName ,count(teacherName) as num from examininterviewrecord where pdate >'${detail_startime}' and pdate < '${detail_endtime}' GROUP BY teacherName " />
- <property name="rowMapper" ref="teacherInterviewMapper">
- </property>
- </bean>
- </beans>
读取数据 teacherInterviewMapper
- package com.yc.batch;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.stereotype.Component;
- import com.yc.vo.TeacherInterviewdetail;
- import com.yc.vo.TeacherWorkdetail;
- import com.yc.vo.Workdetail;
- @Component("teacherInterviewMapper")
- public class TeacherInterviewMapper implements RowMapper {
- @Override
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- TeacherInterviewdetail TId=new TeacherInterviewdetail();
- TId.setTeacherName(rs.getString("teacherName"));
- TId.setNum(rs.getInt("num"));
- return TId;
- }
- }
处理数据 teacherInterviewProcessor ,这个处理数据方法,一般都是在这里在这里进行一些数据的加工,比如有些数据没有读到,你也可以在这个方法和后面那个写入数据的类里面写,所以就导致了这个类里面你可以什么都不敢,直接把数据抛到后面去,让后面的写数据类来处理;我这里就是处理数据的这个类什么都没写,但是最好还是按它的规则来!
- package com.yc.batch;
- import org.hibernate.engine.transaction.jta.platform.internal.SynchronizationRegistryBasedSynchronizationStrategy;
- import org.springframework.batch.item.ItemProcessor;
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Service;
- import com.yc.vo.TeacherInterviewdetail;
- import com.yc.vo.TeacherWorkdetail;
- import com.yc.vo.Workdetail;
- //业务层
- @Component("teacherInterviewProcessor")
- public class TeacherInterviewProcessor implements ItemProcessor<TeacherInterviewdetail, TeacherInterviewdetail> {
- @Override
- public TeacherInterviewdetail process(TeacherInterviewdetail teacherInterviewdetail) throws Exception {
- return teacherInterviewdetail;
- }
- }
写数据 teacherInterviewItemWriter 这个类里面主要是把数据写进一个文件里,同时我这个类里面还有一些数据处理
- package com.yc.batch;
- import java.io.InputStream;
- import java.text.NumberFormat;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Properties;
- import javax.annotation.Resource;
- import org.springframework.batch.item.ItemWriter;
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Service;
- import com.yc.biz.ExamineeClassBiz;
- import com.yc.biz.WorkBiz;
- import com.yc.utils.CsvUtils;
- import com.yc.vo.TeacherInterviewdetail;
- import com.yc.vo.TeacherWorkdetail;
- import com.yc.vo.Workdetail;
- import net.sf.ehcache.util.PropertyUtil;
- //写
- @Component("teacherInterviewItemWriter")
- public class TeacherInterviewItemWriter implements ItemWriter<TeacherInterviewdetail>{
- @Override
- public void write(List<? extends TeacherInterviewdetail> teacherInterviewdetails) throws Exception {
- Properties props = new Properties();
- InputStream in= PropertyUtil.class.getClassLoader().getResourceAsStream("connectionConfig.properties");
- props.load(in);
- String time=props.getProperty("detail_time");
- CsvUtils cu=new CsvUtils();
- List<Object> works=new ArrayList<Object>();
- for(TeacherInterviewdetail t:teacherInterviewdetails){
- works.add(t);
- }
- String path=this.getClass().getResource("/").getPath();
- path=path.substring(0,path.lastIndexOf("/"));
- path=path.substring(0,path.lastIndexOf("/"));
- path=path.substring(0,path.lastIndexOf("/"));
- path=path.substring(0,path.lastIndexOf("/"));
- cu.writeCsv(path+"/csv/teacherInterview_"+time+".csv",works );
- }
- }
我这里有用到一个吧数据写进CSV文件的jar包
- <span style="white-space:pre;"> </span><dependency>
- <groupId>net.sourceforge.javacsv</groupId>
- <artifactId>javacsv</artifactId>
- <version>2.0</version>
- </dependency>
CsvUtils帮助类的写入CSV文件方法
- /**
- * 写入CSV文件
- * @throws IOException
- */
- public void writeCsv(String path,List<Object> t) throws IOException{
- String csvFilePath = path;
- String filepath=path.substring(0,path.lastIndexOf("/"));
- File f=new File(filepath);
- if(!f.exists()){
- f.mkdirs();
- }
- File file=new File(path);
- if(!file.exists()){
- file.createNewFile();
- }
- CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("GBK"));
- try {
- for(Object obj:t){
- String[] contents=obj.toString().split(",");
- wr.writeRecord(contents);
- }
- wr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
就这样一个基本的batch流程就跑起来了,它通过从数据里读取一些数据,然后经过处理后,被存进服务器下的一个文件里面,之后像这种数据的读取就不需要去数据库里面
查询了,而是可以直接通过读取CSV文件来处理这个业务。一般使用这个的都会配一个定时器,让它们每隔一段时间跑一次,从而获得较新的数据
下面是定时器的配置
定时器的配置非常简单,我是使用注解方式来配置的
定时器任务类
- package com.yc.task.impl;
- import javax.transaction.Transactional;
- import org.springframework.batch.core.JobParametersInvalidException;
- import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
- import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
- import org.springframework.batch.core.repository.JobRestartException;
- import org.springframework.batch.item.ItemProcessor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Service;
- import com.yc.batch.ClassBatch;
- import com.yc.batch.MessageItemBatch;
- import com.yc.batch.TeacherInterviewBatch;
- import com.yc.batch.TearcherBatch;
- import com.yc.po.Work;
- import com.yc.task.WorkTask;
- import com.yc.vo.Workdetail;
- @Service
- public class WorkTaskImpl implements WorkTask{
- @Autowired
- private TeacherInterviewBatch teacherInterviewBatch;//教师访谈记录
- public void setTeacherInterviewBatch(TeacherInterviewBatch teacherInterviewBatch) {
- this.teacherInterviewBatch = teacherInterviewBatch;
- }
- @Scheduled(cron= "0 30 22 * * ?") //每天晚上十点30执行一次 这个注解会让框架会自动把这个方法看成任务启动方法
- @Override
- public void task() {
- try {
- teacherInterviewBatch.test();//教师访谈
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
定时器所真正要执行的方法
- package com.yc.batch;
- import javax.annotation.Resource;
- import org.apache.commons.jexl2.Main;
- 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.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.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- @Component
- public class TeacherInterviewBatch {
- private Job job;
- private JobLauncher launcher;
- @Resource(name="writerteacherInterview")
- public void setJob(Job job) {
- this.job = job;
- }
- @Autowired
- public void setLauncher(JobLauncher launcher) {
- this.launcher = launcher;
- }
- public void test() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException{
- JobParameters jobParameters =
- new JobParametersBuilder()
- .addLong("time",System.currentTimeMillis()).toJobParameters();
- JobExecution result = launcher.run(job, jobParameters);
- }
- }
就这样batch就被定时器调度起来了,每天十点准时使用batch来操作数据
转自:https://blog.csdn.net/pttaoge/article/details/76684656
spring batch的使用和定时器Quart的使用的更多相关文章
- Spring Batch在大型企业中的最佳实践
在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后进行一系列的后续处理.这样的过程就是" ...
- spring batch资料收集
spring batch官网 Spring Batch在大型企业中的最佳实践 一篇文章全面解析大数据批处理框架Spring Batch Spring Batch系列总括
- Spring Batch学习笔记三:JobRepository
此系列博客皆为学习Spring Batch时的一些笔记: Spring Batch Job在运行时有很多元数据,这些元数据一般会被保存在内存或者数据库中,由于Spring Batch在默认配置是使用H ...
- Spring Batch学习笔记二
此系列博客皆为学习Spring Batch时的一些笔记: Spring Batch的架构 一个Batch Job是指一系列有序的Step的集合,它们作为预定义流程的一部分而被执行: Step代表一个自 ...
- 初探Spring Batch
此系列博客皆为学习Spring Batch时的一些笔记: 为什么我们需要批处理? 我们不会总是想要立即得到需要的信息,批处理允许我们在请求处理之前就一个既定的流程开始搜集信息:比如说一个银行对账单,我 ...
- Spring Batch 中文参考文档 V3.0.6 - 1 Spring Batch介绍
1 Spring Batch介绍 企业领域中许多应用系统需要采用批处理的方式在特定环境中运行业务操作任务.这种业务作业包括自动化,大量信息的复杂操作,他们不需要人工干预,并能高效运行.这些典型作业包括 ...
- Spring Batch 批处理框架
<Spring Batch 批处理框架>基本信息作者: 刘相 出版社:电子工业出版社ISBN:9787121252419上架时间:2015-1-24出版日期:2015 年2月开本:16开页 ...
- [Spring Batch] 图解Spring Batch原理
找到一副以前学习的图,稻清楚的描述了Spring Batch运行原理:
- Spring Batch实践
Spring Batch在大型企业中的最佳实践 在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后 ...
随机推荐
- Java开发微信公众号(三)---微信服务器请求消息,响应消息,事件消息以及工具处理类的封装
在前面几篇文章我们讲了微信公众号环境的配置 和微信公众号服务的接入,接下来我们来说一下微信服务器请求消息,响应消息以及事件消息的相关内容,首先我们来分析一下消息类型和返回xml格式及实体类的封装. ( ...
- k8s与CICD--借助scp插件实现非容器项目的部署
一直没有时间完成drone系列文章.drone-wechat插件实现了一半,由于企业微信token申请比较麻烦,所以也没有进展.今天抽出时间,研究了一下scp插件,主要目的是实现非容器项目的部署.其实 ...
- c++ 中的slipt实现
来自 http://www.cnblogs.com/dfcao/p/cpp-FAQ-split.html http://blog.diveinedu.com/%E4%B8%89%E7%A7%8D%E5 ...
- win7分盘(复制)
1/10 右击“计算机”选择“管理” 2/10 打开管理之后点击“磁盘管理器”,在想要新建磁盘的分区上右击,点击“压缩卷” 3/10 在“输入压缩空间量”后面输入需要新建磁盘的大小,输入的单位为MB( ...
- nyoj 题目14 会场安排问题
会场安排问题 时间限制:3000 ms | 内存限制:65535 KB 难度:4 描述 学校的小礼堂每天都会有许多活动,有时间这些活动的计划时间会发生冲突,需要选择出一些活动进行举办.小刘的工 ...
- C#中的is和as的转型区别
摘自CLR via C#第三版第四章 在c#中is可以用来判断一个对象是否兼容给定的类型,如果是返回true,否则返回false. 同时is是永不会抛出异常的.如果对象引用是null,is操作符总是返 ...
- centos6.5 mysql忘记登入密码
1.修改文件目录为/etc/my.cnf的文件; 在[mysqld]的段中加上一句:skip-grant-tables,保存文件重启数据库: 例如: [mysqld] skip-grant-table ...
- Js 中 == 与 === 的区别
1.对于string,number等基础类型,==和===是有区别的 1)不同类型间比较,==之比较“转化成同一类型后的值”看“值”是否相等,===如果类型不同,其结果就是不等 2)同类型比较,直接进 ...
- Intellij热部署插件JRebel
Intellij热部署插件JRebel 安装JRebel 激活JRebel 相关设置 Intellij热部署插件JRebel 项目需求,一直用eclipse的我,也要改用IDEA了,一开始,很不习惯. ...
- 【UVA11859】Division Game(SG函数,Nim游戏)
题意:给定一个n*m的矩阵,两个游戏者轮流操作. 每次可以选一行中的1个或多个大于1的整数,把它们中的每个数都变成它的某个真因子,不能操作的输. 问先手能否获胜 n,m<=50,2<=a[ ...