Spring Batch

Preview:

Citation preview

Entreprise Integration with Springformation proposée par Zenika Paris

Formation officielle Spring SourceFormation certifiante : donnant le droit de passer lacertification Spring.Durée 4 joursFormation 50% théorie, 50% pratiqueFormation animée par Grégory Boissinot

AgendaJour 1

Introduction aux différents styles d'intégrationTâches et ordonnancementRemotingSOAP web services

AgendaJour 2

Advanced Web servicesRESTful web servicesWorking with JMSTransactional JMS

AgendaJour 3

Global transaction management (XA & JTA)Spring Integration

AgendaJour 4

Spring BatchSpring Batch Admin

Spring BatchPhilosophie de traitement répétitif de volumes importants de

données sans interactions humaines.

Présentation du cadre de spring batchUn Job est constitué de Steps.Une Step est constituée de ItemReader, ItemProcessor,ItemWriterUne JobInstance est constituée d'un Job et de JobParametersUne tentative exécution d'une JobInstance est uneJobExecutionLes meta data d'une JobExecution sont enregistréee dans leJobRepositoryLe JobLauncher est en charge de lancer les Jobs

Architecture

Présentation d'une StepTraitement par lot : Chunk oriented Step.

Configuration d'un jobTraitement par lot : Chunk oriented Step.

<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"  xmlns:batch="http://www.springframework.org/schema/batch"  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring‐beans‐3.0.xsd   http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring‐batch‐2.1.xsd"<batch:job id="diningRequestsJob">  <batch:step id="diningRequestsStep">   <batch:tasklet start‐limit="3">    <batch:chunk reader="diningRequestsReader"        writer="reportWriter"        commit‐interval="10">     <batch:processor adapter‐method="rewardAccountFor">      <ref bean="rewardNetwork"/>     </batch:processor>    </batch:chunk>   </batch:tasklet>  </batch:step></batch:job>

ItemReader & ItemWriteroff-the-shelf components

filexmljdbcHibernateJMS

Possibilité de créer ces propres reader et writer en implémentantles interfaces : ItemReader et ItemWriter

ItemReader & ItemWriterItemReader

AmqpItemReader AggregateItemReaderFlatFileItemReader HibernateCursorItemReaderHibernatePagingItemReader IbatisPagingItemReaderItemReaderAdapter JdbcCursorItemReaderJdbcPagingItemReader JmsItemReaderJpaPagingItemReader ListItemReaderMongoItemReader Neo4jItemReaderRepositoryItemReader StoredProcedureItemReaderStaxEventItemReader

ItemReader & ItemWriterItemWriter

AbstractItemStreamItemWriter AmqpItemWriterCompositeItemWriter FlatFileItemWriterGemfireItemWriter HibernateItemWriterIbatisBatchItemWriter ItemWriterAdapterJdbcBatchItemWriter JmsItemWriterJpaItemWriter MimeMessageItemWriterMongoItemWriter Neo4jItemWriterStaxEventItemWriter RepositoryItemWriter

JobRepositoryEnregistrement des informations des JobExecution : Job

Context, Step Context, Job Instance, Job Params.Enregistrement volatile (en mémoire) ou persisté (en base de

données relationnelle).

MapJobRepositoryFactoryBeanA FactoryBean that automates the creation of a

SimpleJobRepository using non-persistent in-memory DAOimplementations.

<bean id="jobRegistry" class="org.springframework.batch...MapJobRegistry">   <property name="transactionManager" ref="transactionManager"></property></bean>

JobRepositoryFactoryBeanA FactoryBean that automates the creation of a

SimpleJobRepository using JDBC DAO implementations whichpersist batch metadata in database.

<bean id="jobRepository" class="org...JobRepositoryFactoryBean">    <property name="dataSource" ref="dataSource"/></bean>

Restart and RecoveryGestion de l'état et des exécutions pour permettre le

redémarrage et la récupération en cas d'erreur.

ExecutionContextUtilisation de Job ExecutionContext fournissant l'état initial

pour un redémarrage. Step ExecutionContext committé à la finde chaque chunk, permet de reprendre une exécution.

Possibilité d'utiliser les annotations et

Stateful ItemReader/WriterPermet d'enregister au sein du context d'exécution des valeurs

afin de permettre la reprise. Attention à la gestion de l'état si les steps sont multi-threadées.

Interface StepExecutionListener avec les méthodes :void   beforeStep(StepExecution stepExecution)ExitStatus   afterStep(StepExecution stepExecution)

BeforeStep AfterStep

Interface implémentée par la plupart des readers founit. Exemple:

ItemStreamFacilitation de la gestion d'état pour ItemReader :

open() appelé avant chaque appel à la méthode readupdate() appelé à la fin de chaque chunk, avant le commitclose() appelé à la fin de chaque step

FlatFileItemReaderRestartable ItemReader that reads lines from input

setResource(Resource)

FieldSet et FieldSetMapperDans le cadre de la lecture de fichier, Spring fournit une

représentation de la ligne lue grâce à un wrapper : FieldSet. Le FieldSet est ensuite transformé sous forme d'objet grâce à

un FieldSetMapper.

FieldSet et FieldSetMapperSpring founit des mappers tels que :

PassthourghFieldSetMapper: retourne le fieldset tel quel.BeanWrapperFieldSetMapper: utiliser le noms des champspour mapper avec les propriétes d'un objet.

Partage d'état entre StepUtilisation du JobExecutionContext

@BeforeSteppublic void retrieveInterstepData(StepExecution stepExecution) {  JobExecution jobExecution = stepExecution.getJobExecution();  ExecutionContext jobContext = jobExecution.getExecutionContext();  jobContext.get("sharedObject");}

Partage d'état entre StepUtilisation du ExecutionContextPromotionListener

<bean id="promotionListener" class="org...ExecutionContextPromotionListener">  <property name="key" value="myKey" /></bean>

Scope StepUtilisation de SpEL pour injecter dynamiquement les parametres

du job.<bean id="reader" scope="step" class="MyReader">  <property name="resource" value="#{jobParameters['input.resource.path']}">  </property></bean>

Skip, Retry, Repeat, RestartRepeat : lorsqu'on souhaite itérer sur une collection deressourcesRetry : lors d'une erreur non attribuable à la tâcheSkip : toutes les erreurs ne sont pas causes d'échecRestart : redémarrage

On ne parle plus d'une chunk oriented step.

Repeatpackage org.springframework.batch.core.step.tasklet;

import org.springframework.batch.core.StepContribution;import org.springframework.batch.core.scope.context.ChunkContext;import org.springframework.batch.repeat.RepeatStatus;

public interface Tasklet {    RepeatStatus execute(StepContribution contribution,                          ChunkContext chunkContext) throws Exception;}

Retry<step id="step1">  <tasklet>   <chunk reader="reader" writer="writer" commit‐interval="20" retry‐limit="3">   <retryable‐exception‐classes>    <include class="org...DeadLockLoserDataAccessException" />   </retryable‐exception‐classes>   </chunk>  </tasklet></step>

Skip<step id="step1">  <tasklet>   <chunk reader="reader" writer="writer" commit‐interval="20" skip‐limit="3">   <skippable‐exception‐classes>    <include class="org...FlatFileParseException" />   </skippable‐exception‐classes>   </chunk>  </tasklet></step>

RestartSpring Batch utilise le contexte persisté où relance la tâchefrom scratch.Possibilité de désactiver le redémarrage de steps <taskletallow‐start‐if‐complete="true">Possibilité de limiter le nombre de démarrage d'une step :<tasklet start‐limit="1">

ListenersCallback au cours de l'exécution (logging, auditing, state, errorhandling, etc.)JobExecutionListenerStepListenerStepExecution-, Chunk-, Item(Read|Processor|Writer)- etSkipListener

ListenersAfterChunk AfterChunkError AfterJob AfterProcessAfterRead AfterStep AfterWrite BeforeChunkBeforeJob BeforeProcess BeforeRead BeforeStepBeforeWrite OnProcessError OnReadError OnSkipInProcessOnSkipInRead OnSkipInWrite OnWriteError

Pour allez plus loinJobParametersValidator JobExplorerJobOperator CommandLineJobRunnerJobExecutionDecider

JobExplorerpublic interface JobExplorer {

    List<JobInstance> getJobInstances(String jobName, int start, int count);

    JobExecution getJobExecution(Long executionId);

    StepExecution getStepExecution(Long jobExecutionId, Long stepExecutionId);

    JobInstance getJobInstance(Long instanceId);

    List<JobExecution> getJobExecutions(JobInstance jobInstance);

    Set<JobExecution> findRunningJobExecutions(String jobName);}

JobOperatorpublic interface JobOperator {

    List<Long> getExecutions(long instanceId) throws NoSuchJobInstanceException;

    List<Long> getJobInstances(String jobName, int start, int count)          throws NoSuchJobException;

    Set<Long> getRunningExecutions(String jobName) throws NoSuchJobException;

    String getParameters(long executionId) throws NoSuchJobExecutionException;

    Long start(String jobName, String parameters)          throws NoSuchJobException, JobInstanceAlreadyExistsException;

    Long restart(long executionId)          throws JobInstanceAlreadyCompleteException, NoSuchJobExecutionException,                  NoSuchJobException, JobRestartException;

    Long startNextInstance(String jobName)          throws NoSuchJobException, JobParametersNotFoundException, JobRestartException,                 JobExecutionAlreadyRunningException, JobInstanceAlreadyCompleteException;

    boolean stop(long executionId)          throws NoSuchJobExecutionException, JobExecutionNotRunningException;

    String getSummary(long executionId) throws NoSuchJobExecutionException;

    Map<Long, String> getStepExecutionSummaries(long executionId)          throws NoSuchJobExecutionException;

Scaling and parallel processingA utiliser seulement en cas de nécessaire besoin.

Multi-threaded StepParallel StepRemote Chunking Step (spring-batch-integration)Partitionning Step

Il suffit d'ajouter un

Multi-threaded StepTaskExecutor

<step id="loading">  <tasklet task‐executor="taskExecutor" throttle‐limit="20" /></step>      

Item(Reader|Writer|Processor) doivent être stateless outhread-safeLa plupart des Items fournit par Spring Batch ne sont pasthread-safethrottle-limit correspond au nombre de threads disponibles

Parallel Step<job id="job">  <split id="split" task‐executor="taskExecutor" next="step4">   <flow>    <step id="step1" parent="s1" next="step2" />    <step id="step2" parent="s2" />   </flow>   <flow>    <step id="step3" parent="s3" />   </flow>  </split>  <step id="step4" parent="s4" /></job>      

Partitioning SPICela consiste en :

Une implémentation de Step dite PartitionStepPartitionHandlerStepExecutionSplitter

Partitioning SPI

Spring Batch AdminSous projet de Spring BatchSous la forme d'un war ou d'un jarfournit une interface web et une API RESTFul pour inspecterles jobsse branche sur les meta datas persistées par leJobRepository

Spring Batch Admin

Spring Batch Admin

Spring Batch Admin

Recommended