百度云案例下载地址:
spring batch批量读取txt文件demo案例下载:链接:https://pan.baidu.com/s/1gfRP0cF 密码:uxni
启动:找到SpringbatchApplication,右键--run as --java application(springboot启动方式)
目录结构:
1、springBatch的job的step方法有reader,processor,writer方法。
reader从本地文件读取内容,processor对读取的每行数据进行处理的过程,writer,将处理过的数据进行存储操作。
(1)第一种启动springbatch创建job方式
尽量不要用@Autowired(required = false)
package com.feeling.mc.batch.control;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.feeling.mc.common.utils.DateUtil;
import com.feeling.mc.db.entity.BatchManager;
import com.feeling.mc.db.mapper.messager.BatchManagerMapper;
@Component
public class DemoController implements ApplicationContextAware{
@Autowired(required = false)
JobLauncher jobLauncher;
private ApplicationContext applicationContext;
public JobParameters jobParameters;
@Autowired
private BatchManagerMapper managerMapper;
//@Scheduled(cron = "0 0 8 * * ?") // 早上8点
// 每分钟跑一次
@Scheduled(cron = "0 0/1 * * * ?")
public void imp() throws Exception {
Job job = (Job)this.applicationContext.getBean("ReaderBatchMessage");
jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();
jobLauncher.run(job, jobParameters);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
(2)第二种启动springbatch创建job方式
在SpringbatchApplication加上@EnableScheduling//定时器
package com.feeling.batch.controller;
import javax.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class BatchController {
@Autowired
JobLauncher jobLauncher;
@Autowired
JobOperator jobOperator;
@Resource(name="messagebatchinsertjo