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包
<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>
<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>
<!--一个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包
<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;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# spring
# batch
# 定时器
# quartz
# 使用
# Java中批处理框架spring batch详细介绍
# 详解SpringBoot和SpringBatch 使用
# 基于Spring Batch向Elasticsearch批量导入数据示例
# 详解Spring batch 入门学习教程(附源码)
# 浅谈Spring Batch在大型企业中的最佳实践
# Spring Batch入门教程篇
# Spring Batch读取txt文件并写入数据库的方法教程
# Spring batch批处理框架
# spring batch 读取多个文件数据导入数据库示例
# 详解批处理框架之Spring Batch
# 在这里
# 写进
# 的是
# 都是
# 是一个
# 我是
# 在这个
# 你可以
# 多个
# 有可能
# 就有
# 要去
# 批处理
# 这样一个
# 会让
# 可以直接
# 数据处理
# 不需
# 还有一些
# 你也可以
相关文章:
高防服务器租用如何选择配置与防御等级?
如何快速生成高效建站系统源代码?
建站之星24小时客服电话如何获取?
微课制作网站有哪些,微课网怎么进?
韩国代理服务器如何选?解析IP设置技巧与跨境访问优化指南
公司门户网站制作流程,华为官网怎么做?
建站主机选购指南与交易推荐:核心配置解析
已有域名和空间如何搭建网站?
南京网站制作费用,南京远驱官方网站?
标准网站视频模板制作软件,现在有哪个网站的视频编辑素材最齐全的,背景音乐、音效等?
单页制作网站有哪些,朋友给我发了一个单页网站,我应该怎么修改才能把他变成自己的呢,请求高手指点迷津?
如何用AWS免费套餐快速搭建高效网站?
建站VPS配置与SEO优化指南:关键词排名提升策略
购物网站制作费用多少,开办网上购物网站,需要办理哪些手续?
青岛网站建设如何选择本地服务器?
定制建站流程解析:需求评估与SEO优化功能开发指南
网站制作中优化长尾关键字挖掘的技巧,建一个视频网站需要多少钱?
如何通过建站之星自助学习解决操作问题?
如何高效完成自助建站业务培训?
宁波自助建站系统如何快速打造专业企业网站?
杭州银行网站设计制作流程,杭州银行怎么开通认证方式?
广东企业建站网站优化与SEO营销核心策略指南
宝塔建站后网页无法访问如何解决?
枣阳网站制作,阳新火车站打的到仙岛湖多少钱?
专业网站制作服务公司,有哪些网站可以免费发布招聘信息?
广平建站公司哪家专业可靠?如何选择?
在线制作视频网站免费,都有哪些好的动漫网站?
北京网站制作公司哪家好一点,北京租房网站有哪些?
如何通过虚拟机搭建网站?详细步骤解析
网站制作需要会哪些技术,建立一个网站要花费多少?
怎么制作一个起泡网,水泡粪全漏粪育肥舍冬季氨气超过25ppm,可以有哪些措施降低舍内氨气水平?
制作网站公司那家好,网络公司是做什么的?
婚礼视频制作网站,学习*后期制作的网站有哪些?
如何通过FTP空间快速搭建安全高效网站?
免费制作海报的网站,哪位做平面的朋友告诉我用什么软件做海报比较好?ps还是cd还是ai这几个软件我都会些我是做网页的?
广州网站制作的公司,现在专门做网站的公司有没有哪几家是比较好的,性价比高,模板也多的?
建站上传速度慢?如何优化加速网站加载效率?
建站之星如何助力企业快速打造五合一网站?
如何优化Golang Web性能_Golang HTTP服务器性能提升方法
百度网页制作网站有哪些,谁能告诉我百度网站是怎么联系?
如何在阿里云服务器自主搭建网站?
七夕网站制作视频,七夕大促活动怎么报名?
临沂网站制作公司有哪些,临沂第四中学官网?
成都响应式网站开发,dw怎么把手机适应页面变成网页?
php json中文编码为null的解决办法
建站之星IIS配置教程:代码生成技巧与站点搭建指南
如何通过PHP快速构建高效问答网站功能?
用v-html解决Vue.js渲染中html标签不被解析的问题
c++怎么用jemalloc c++替换默认内存分配器【性能】
建站之星在线客服如何快速接入解答?
*请认真填写需求信息,我们会在24小时内与您取得联系。