Spring Batch教程(五)spring boot实现batch功能注解示例:读写文本文件(读取一行数据,针对一行数据进行求和)

news2024/10/6 6:03:33

Spring batch 系列文章

Spring Batch教程(一) 简单的介绍以及通过springbatch将xml文件转成txt文件
Spring Batch教程(二)示例:将txt文件转成xml文件以及读取xml文件内容存储到数据库mysql
Spring Batch教程(三)示例:从mysql中读取数据写入文本和从多个文本中读取内容写入mysql
Spring Batch教程(四)tasklet使用示例:spring batch的定时任务使用
Spring Batch教程(五)spring boot实现batch功能注解示例:读写文本文件
Spring Batch教程(六)spring boot实现batch功能注解示例:读文件写入mysql


文章目录

  • Spring batch 系列文章
  • 一、示例1:读取文本文件写文本文件
    • 1、maven依赖
    • 2、java bean
      • 1)、Student
      • 2)、StudentTotalScore
    • 3、配置spring batch的ItemReader、ItemWriter和ItemProcessor
    • 4、创建ItemProcessor实现类
    • 5、创建一个运行job的main类
    • 6、准备测试数据
    • 7、验证


本文介绍了1个示例,即通过spring boot 启动spring batch的任务,该任务是通过注解实现的。
本文使用的是jdk8版本,最新版本的spring core和springb batch用不了。

一、示例1:读取文本文件写文本文件

本示例是读取一行数据,针对一行数据进行求和。

1、maven依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-batch</artifactId>
			<version>2.3.12.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.2</version>
			<scope>provided</scope>
		</dependency>

2、java bean

1)、Student

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 
 * @author alanchan
 *
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
	private String id;
	private int chinese;
	private int math;
	private int english;

}

2)、StudentTotalScore

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 
 * @author alanchan
 *
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentTotalScore {
	private String id;
	private int totalScore;

}

3、配置spring batch的ItemReader、ItemWriter和ItemProcessor

逻辑上与spring batch一致


import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

import com.win.byannotation.bean.Student;
import com.win.byannotation.bean.StudentTotalScore;

/**
 * 
 * @author alanchan
 *
 */
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
	private final String inputFiles = "student-data.txt";
	private final String outputFiles = "d:/studentscore-data.txt";
//	private final String outputFiles = "studentscore-data.txt";

	@Bean
	public ItemReader<Student> reader() {
		FlatFileItemReader<Student> reader = new FlatFileItemReader<Student>();
		reader.setResource(new ClassPathResource(inputFiles));
		reader.setLineMapper(new DefaultLineMapper<Student>() {
			{
				setLineTokenizer(new DelimitedLineTokenizer() {
					{
						setNames(new String[] { "id", "chinese", "math", "english" });
					}
				});
				setFieldSetMapper(new BeanWrapperFieldSetMapper<Student>() {
					{
						setTargetType(Student.class);
					}
				});
			}
		});
		return reader;
	}

	@Bean
	public ItemWriter<StudentTotalScore> writer() {
		FlatFileItemWriter<StudentTotalScore> writer = new FlatFileItemWriter<StudentTotalScore>();
		writer.setResource(new FileSystemResource(outputFiles));
//		writer.setResource(new ClassPathResource(outputFiles));
		DelimitedLineAggregator<StudentTotalScore> delLineAgg = new DelimitedLineAggregator<StudentTotalScore>();
		delLineAgg.setDelimiter(",");
		BeanWrapperFieldExtractor<StudentTotalScore> fieldExtractor = new BeanWrapperFieldExtractor<StudentTotalScore>();
		fieldExtractor.setNames(new String[] { "id", "totalScore" });
		delLineAgg.setFieldExtractor(fieldExtractor);
		writer.setLineAggregator(delLineAgg);
		return writer;
	}

	@Bean
	public ItemProcessor<Student, StudentTotalScore> processor() {
		return new StudentItemProcessor();
	}

	@Bean
	public Job createMarkSheet(JobBuilderFactory jobs, Step step) {
		return jobs.get("createMarkSheet").flow(step).end().build();
	}

	@Bean
	public Step step(StepBuilderFactory stepBuilderFactory, ItemReader<Student> reader, ItemWriter<StudentTotalScore> writer, ItemProcessor<Student, StudentTotalScore> processor) {
		return stepBuilderFactory.get("step").<Student, StudentTotalScore>chunk(5).reader(reader).processor(processor).writer(writer).build();
	}

}

4、创建ItemProcessor实现类


import org.springframework.batch.item.ItemProcessor;

import com.win.byannotation.bean.StudentTotalScore;
import com.win.byannotation.bean.Student;

/**
 * 
 * @author alanchan
 *
 */
public class StudentItemProcessor implements ItemProcessor<Student, StudentTotalScore> {

	@Override
	public StudentTotalScore process(final Student student) throws Exception {
		int totalScore = student.getChinese() + student.getMath() + student.getEnglish();
		System.out.println("student id:" + student.getId() + " and Total score:" + totalScore);
		StudentTotalScore marksheet = new StudentTotalScore(student.getId(), totalScore);
		return marksheet;
	}

}

5、创建一个运行job的main类


import java.io.IOException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

/**
 * 
 * @author alanchan
 *
 */

@ComponentScan
//@EnableAutoConfiguration/@SpringBootApplication 该组件包含数据源配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class App {
	public static void main(String[] args) throws IOException {
		ApplicationContext ctx = SpringApplication.run(App.class, args);
		
	}
}

6、准备测试数据

文件位置:/sping-batch/src/main/resources/student-data.txt

student-1,90,85,96
student-2,92,97,94
student-3,95,93,100

7、验证

启动应用程序,观察输出文件内容
在这里插入图片描述
程序控制台输出

2023-07-21 18:14:07.106  INFO 52200 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler 'quartzScheduler' initialized from an externally provided properties instance.
2023-07-21 18:14:07.106  INFO 52200 --- [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.2.1
2023-07-21 18:14:07.106  INFO 52200 --- [           main] org.quartz.core.QuartzScheduler          : JobFactory set to: org.springframework.scheduling.quartz.SpringBeanJobFactory@410954b
2023-07-21 18:14:07.135  INFO 52200 --- [           main] o.s.s.quartz.SchedulerFactoryBean        : Starting Quartz Scheduler now
2023-07-21 18:14:07.136  INFO 52200 --- [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED started.
2023-07-21 18:14:07.143  INFO 52200 --- [           main] com.win.byannotation.App                 : Started App in 0.92 seconds (JVM running for 1.196)
2023-07-21 18:14:07.145  INFO 52200 --- [           main] o.s.b.a.b.JobLauncherApplicationRunner   : Running default command line with: []
2023-07-21 18:14:07.145  WARN 52200 --- [           main] o.s.b.c.c.a.DefaultBatchConfigurer       : No datasource was provided...using a Map based JobRepository
2023-07-21 18:14:07.145  WARN 52200 --- [           main] o.s.b.c.c.a.DefaultBatchConfigurer       : No transaction manager was provided, using a ResourcelessTransactionManager
2023-07-21 18:14:07.156  INFO 52200 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2023-07-21 18:14:07.183  INFO 52200 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=createMarkSheet]] launched with the following parameters: [{}]
2023-07-21 18:14:07.210  INFO 52200 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step]
student id:student-1 and Total score:271
student id:student-2 and Total score:283
student id:student-3 and Total score:288
2023-07-21 18:14:07.240  INFO 52200 --- [           main] o.s.batch.core.step.AbstractStep         : Step: [step] executed in 30ms
2023-07-21 18:14:07.244  INFO 52200 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=createMarkSheet]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 43ms

以上,通过spring boot 启动spring batch的任务,该任务是通过注解实现的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/800882.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Spring】Spring 总览

一、简单介绍一下 Spring Spring是一个全面的、企业应用开发的一站式解决方案&#xff0c;贯穿表现层、业务层、持久层&#xff0c;可以轻松和其他框架整合&#xff0c;具有轻量级、控制反转、面向切面、容器等特征。 轻量级 &#xff1a; 空间开销和时间开销都很轻量 控制反…

应用无线鼠标中的2.4GHz无线收发芯片

无线键盘和无线鼠标作为现代办公环境中常见的工具&#xff0c;为我们的工作带来了便利。无线键盘和无线鼠标的工作原理都是基于无线技术实现的&#xff0c;其中常见的是2.4GHz无线技术。让我们一起来详细了解一下它们的工作原理。 无线鼠标的原理非常简单,鼠标部分工作与传统鼠…

运放稳定性分析

基础回顾 电路系统的传函 记基本量为&#xff1a; 电量&#xff08;库伦&#xff09; q q q、电流 i i i、电压 e e e、电阻 R R R、电容 C C C、电感 L L L 电阻 e R i R e_RiR eR​iR&#xff0c;阻抗 R R R 电容 q C e C qCe_C qCeC​&#xff0c;故 e C 1 C q 1 C…

K8s 详解(一) K8s 架构和常用命令

&#x1f388; 作者&#xff1a;Linux猿 &#x1f388; 简介&#xff1a;CSDN博客专家&#x1f3c6;&#xff0c;华为云享专家&#x1f3c6;&#xff0c;Linux、C/C、云计算、物联网、面试、刷题、算法尽管咨询我&#xff0c;关注我&#xff0c;有问题私聊&#xff01; &…

芯片制造详解.净洁室的秘密.学习笔记(三)

这是芯片制造系列的第三期跟学up主三圈&#xff0c;这里对其视频内容做了一下整理和归纳&#xff0c;喜欢的可以看原视频。 芯片制造详解03&#xff1a; 洁净室的秘密&#xff5c;为何芯片厂缺人&#xff1f; 芯片制造详解.净洁室的秘密.学习笔记 三 简介一、干净的级别二、芯片…

ClickHouse(四):ClickHouse分布式搭建及其他

进入正文前&#xff0c;感谢宝子们订阅专题、点赞、评论、收藏&#xff01;关注IT贫道&#xff0c;获取高质量博客内容&#xff01; &#x1f3e1;个人主页&#xff1a;含各种IT体系技术,IT贫道_Apache Doris,Kerberos安全认证,大数据OLAP体系技术栈-CSDN博客 &#x1f4cc;订阅…

Python爬虫实例之淘宝商品页面爬取(api接口)

可以使用Python中的requests和BeautifulSoup库来进行网页爬取和数据提取。以下是一个简单的示例&#xff1a; import requests from bs4 import BeautifulSoupdef get_product_data(url):# 发送GET请求&#xff0c;获取网页内容headers {User-Agent: Mozilla/5.0 (Windows NT…

管理类联考——大纲篇

综合能力考试大纲 Ⅰ、考试性质 综合能力考试是为高等院校和科研院所招收管理类专业学位硕士研究生而设置的具有选拔性质的全国联考科目&#xff0c;其目的是科学、公平、有效地测试考生是否具备攻读专业学位所必须的基本素质、一般能力和培养潜能&#xff0c;评价的标准是高…

python自动化测试+unittets框架

我们整个自动化才是报告的环节基本上分为三个部分&#xff1a; 1.测试用例的准备 2.测试用例的执行 3.测试报告的输出 1.测试用例的准备&#xff1a; 那我们就以搜孤网页做一个简单的用例&#xff1a; from selenium import webdriver import unittest class Case_1(unit…

【随机森林-鸢尾花分类】

1. 引言 随机森林是集成学习中的一颗瑞士军刀&#xff0c;它是一种强大的机器学习算法&#xff0c;常用于分类和回归任务。随机森林集合了“三个臭皮匠&#xff0c;顶个诸葛亮”的智慧&#xff0c;通过组合多个决策树的预测结果&#xff0c;来提高模型的鲁棒性和性能。 2. 随…

学习笔记|大模型优质Prompt开发与应用课(二)|第一节:大模型应用密码—Prompt的一千种打开方式

文章目录 第一节:大模型应用密码—Prompt的一千种打开方式01你可能听过一个小故事1910华盛顿纺织厂罢工事件 02 小问题:哪些场景会被提效类目一︰减少重复性工作的成本&#xff08;降本)例如∶做策划初稿、写JD、润色文案prompt生成结果prompt生成结果prompt生成结果promptprom…

个人博客系统项目进行自动化测试

目录 一、项目界面 二、博客系统自动化测试用例 三、自动化测试 1&#xff09;准备工作 2&#xff09;登录界面测试 测试正确的登录案例 登录界面测试出现问题 测试错误的登录案例 3&#xff09;博客列表界面测试 4&#xff09;博客详情界面测试 5&#xff09;博客编辑…

DEVICENET转ETHERNET/IP网关devicenet协议

捷米JM-EIP-DNT&#xff0c;你听说过吗&#xff1f;这是一款自主研发的ETHERNET/IP从站功能的通讯网关&#xff0c;它能够连接DEVICENET总线和ETHERNET/IP网络&#xff0c;从而解决生产管理系统中协议不同造成的数据交换互通问题。 这款产品在工业自动化领域可谓是一大利器&…

【QT 网络云盘客户端】——主窗口界面的设计

目录 1.设计主窗口界面 2.设置窗口的背景图片 3. 自定义标题栏 3.1 设置toolbutton按钮的图片 3.2 设置按钮的大小 3.3 将自定义标题栏添加设置到主页面中 3.4 去除窗口的原标题栏 3.5 设置按钮颜色 3.6 切换页面功能实现 4.我的文件页面的设计 4.1 菜单栏的设计 4…

插件使用权限管理软件(三)WebAPI项目IIS部署

前言 前面完成了WebAPI项目的接口服务类编写工作&#xff0c;接下来讲把项目部署到服务器的IIS上&#xff0c;让系统运行起来。 一. 项目发布 右键项目RightsManagementSystems.Web.Entry 选择“发布”选项 弹出发布选项界面&#xff0c;选择“文件夹”&#xff0c;点击下一步…

【Android知识笔记】UI体系(一)

Activity的显示原理 setContentView 首先开发者Activity的onCreate方法中通常调用的setContentView会委托给Window的setContentView方法: 接下来看Window的创建过程: 可见Window的实现类是PhoneWindow,而PhoneWindow是在Activity创建过程中执行attach Context的时候创建的…

SystemServer进程

前言 在systemServer启动文章中我们讲了在SystemServer.java的main方法里面调用new SystemServer().run&#xff08;&#xff09;方法启动System_server进程。那么我们接着看一下SystemServer.java具体做了哪些事情&#xff1f; ##SystemServer的run方法介绍 frameworks\base…

VictoriaMetrics

VictoriaMetrics是一个开源的时序数据库和监控解决方案&#xff0c;专门用于存储和查询大规模时间序列数据。它的设计灵感来自Prometheus&#xff0c;但在某些方面与Prometheus有所区别&#xff0c;主要关注于提供高性能、高可用性和低资源占用的特点。 一、与Prometheus区别和…

Kotlin Multiplatform 创建多平台分发库

目标&#xff1a;通过本教程学习如何使用 Kotlin Multiplatform Library 创建多平台分发库(iOS&#xff0c;安卓)。 创建一个项目 1、本教程使用的是Android Studio创建 2、选择 新建工程&#xff0c;选择 Kotlin Multiplatform Library 3、点击next 输入需要创建的项目名称以…

第2章 逻辑分页、AutoFac注入、工作单元与仓储

1 CoreCms.Net.Model.ViewModels.Basics.IPageList<T> namespace CoreCms.Net.Model.ViewModels.Basics { ///<typeparam name"T">泛型类型实例(1个指定实体的类型实例)。</typeparam> /// <summary> /// 【逻辑分页列表--接口】 /// <…