45
Entreprise Integration with Spring formation proposée par Zenika Paris

Spring Batch

Embed Size (px)

Citation preview

Page 1: Spring Batch

Entreprise Integration with Springformation proposée par Zenika Paris

Page 2: Spring Batch

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

Page 3: Spring Batch

AgendaJour 1

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

Page 4: Spring Batch

AgendaJour 2

Advanced Web servicesRESTful web servicesWorking with JMSTransactional JMS

Page 5: Spring Batch

AgendaJour 3

Global transaction management (XA & JTA)Spring Integration

Page 6: Spring Batch

AgendaJour 4

Spring BatchSpring Batch Admin

Page 7: Spring Batch

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

données sans interactions humaines.

Page 8: Spring Batch

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

Page 9: Spring Batch

Architecture

Page 10: Spring Batch

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

Page 11: Spring Batch

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>

Page 12: Spring Batch

ItemReader & ItemWriteroff-the-shelf components

filexmljdbcHibernateJMS

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

Page 13: Spring Batch

ItemReader & ItemWriterItemReader

AmqpItemReader AggregateItemReaderFlatFileItemReader HibernateCursorItemReaderHibernatePagingItemReader IbatisPagingItemReaderItemReaderAdapter JdbcCursorItemReaderJdbcPagingItemReader JmsItemReaderJpaPagingItemReader ListItemReaderMongoItemReader Neo4jItemReaderRepositoryItemReader StoredProcedureItemReaderStaxEventItemReader

Page 14: Spring Batch

ItemReader & ItemWriterItemWriter

AbstractItemStreamItemWriter AmqpItemWriterCompositeItemWriter FlatFileItemWriterGemfireItemWriter HibernateItemWriterIbatisBatchItemWriter ItemWriterAdapterJdbcBatchItemWriter JmsItemWriterJpaItemWriter MimeMessageItemWriterMongoItemWriter Neo4jItemWriterStaxEventItemWriter RepositoryItemWriter

Page 15: Spring Batch

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).

Page 16: Spring Batch

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>

Page 17: Spring Batch

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>

Page 18: Spring Batch

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

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

Page 19: Spring Batch

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.

Page 20: Spring Batch

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

Page 21: Spring Batch

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)

Page 22: Spring Batch

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.

Page 23: Spring Batch

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.

Page 24: Spring Batch

Partage d'état entre StepUtilisation du JobExecutionContext

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

Page 25: Spring Batch

Partage d'état entre StepUtilisation du ExecutionContextPromotionListener

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

Page 26: Spring Batch

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>

Page 27: Spring Batch

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

Page 28: Spring Batch

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;}

Page 29: Spring Batch

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>

Page 30: Spring Batch

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>

Page 31: Spring Batch

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">

Page 32: Spring Batch

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

Page 33: Spring Batch

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

Page 34: Spring Batch

Pour allez plus loinJobParametersValidator JobExplorerJobOperator CommandLineJobRunnerJobExecutionDecider

Page 35: Spring Batch

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);}

Page 36: Spring Batch

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;

Page 37: Spring Batch

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

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

Page 38: Spring Batch

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

Page 39: Spring Batch

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>      

Page 40: Spring Batch

Partitioning SPICela consiste en :

Une implémentation de Step dite PartitionStepPartitionHandlerStepExecutionSplitter

Page 41: Spring Batch

Partitioning SPI

Page 42: Spring Batch

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

Page 43: Spring Batch

Spring Batch Admin

Page 44: Spring Batch

Spring Batch Admin

Page 45: Spring Batch

Spring Batch Admin