[SpringBatch] State

JAVA/SpringBatch|2020. 3. 25. 20:07

Flow 내부에 Step 및 정보들은 모두 State로 이루어져 있어서 State 클래스들은 어떻게 구성되었는지 볼겸 정리

  • [I] State
    • [AC] AbstractState
      • [C] StepState
        • [C] JsrStepState
      • [C] DecisionState
      • [C] FlowState
      • [C] SplitState
        • [C] JsrSplitState
      • [C] DelegateState
      • [C] EndState
        • [C] JsrEndState

State
State에 도메인 인터페이스

  • 메소드
    • FlowExecutionStatus handle(FlowExecutor) : 해당 State를 처리하는 메소드, 상태는 String을 반환할 수 있지만, 특정 동작 상태들은 상수로 정의되어있다.
    • isEndState() : 마지막 State라면 true 리턴, 계속 처리 해야한다면 false를 리턴

AbstractState
보통 추상클래스에 공통로직들이 있는데, State는 공통로직이 거의 없다.

StepState
Step을 wrapping한 State인 만큼 Step을 변수로 가지고 있다.

  • 변수
    • Step : 자신에 해당하는 Step을 변수로 가짐
  • 메소드
    • FlowExecutionStatus handle(FlowExecutor) : Step을 FlowExecutor를 통해 실행

DecisionState
JobExecutionDecider 를 Wrapping 하고 있는 State

  • 변수
    • JobExecutionDecider : FlowExecutionStatus를 반환하는 decider

FlowState
Flow을 wrapping한 State인 만큼 Flow을 변수로 가지고 있다.

  • 변수
    • Flow : 자신에 해당하는 Flow을 변수로 가짐

SplitState
Flow를 병렬 처리 할경우 사용

  • 변수
    • Collection<Flow> : Split에 해당하는 Flow들
    • TaskExecutor : Flow들을 실행하는데 활용되는 Executor
    • FlowExecutionAggregator : 실행 후 aggregation에 활용
  • 메소드
    • FlowExecutionStatus handle(FlowExecutor) : 가지고 있는 Flow들을 실행, task들을 모두 기다리고 마지막에 aggregation

DelegateState
State Proxy에 활용

EndState
Job의 종료 관련

댓글()

[Spring] Spring Batch Reader Writer

JAVA/SpringBatch|2020. 3. 24. 19:57

20.04.02 업데이트

 

Reader(19개)

FlatFileItemReader 

ItemReaderAdapter 

AggregateItemReader 

AbstractItemCountingItemStreamItemReader
AmqpItemReader
KafkaItemReader
HibernateCursorItemReader
HibernatePagingItemReader
JdbcCursorItemReader
JdbcPagingItemReader
JmsItemReader
JpaPagingItemReader
ListItemReader
MongoItemReader
Neo4jItemReader
RepositoryItemReader
StoredProcedureItemReader
StaxEventItemReader
JsonItemReader

 

FlatFileItemReader : Resource(주로 파일일듯)에 대해 코딩없이 간단히 처리 할 수 있도록 제공하는 Reader

setLineMapper()를 통해 라인 한줄 한줄을 Object로 매핑하는 룰을 세팅

FlatFileItemReader reader = new FlatFileItemReader();
     reader.setResource(inputResource1);
     reader.setLineMapper(new PassThroughLineMapper());

 

ItemReaderAdapter : AbstractMethodInvokingDelegator를 상속받은 ItemReader, 결국 리플렉션으로 설정 Object에 원하는 메소드를 ItemReader에 read()호출시 불리도록 하는 Adapter 클래스

 

 

 

 

Writer(18개)

FlatFileItemWriter : 간단 설정(LineSeparator 등)으로 Resource(거의 파일) 을 처리하는 Writer

CompositeItemWriter : 여러개의 Writer를 묶는 Composite Writer

AbstractItemStreamItemWriter
AmqpItemWriter
GemfireItemWriter
HibernateItemWriter
ItemWriterAdapter
JdbcBatchItemWriter
JmsItemWriter
JpaItemWriter
KafkaItemWriter
MimeMessageItemWriter
MongoItemWriter
Neo4jItemWriter
PropertyExtractingDelegatingItemWriter
RepositoryItemWriter
StaxEventItemWriter
JsonFileItemWriter

 

추후 하나씩 정리

 

출처 : https://docs.spring.io/spring-batch/docs/4.2.x/reference/html/appendix.html#listOfReadersAndWriters

댓글()

[Spring Batch] Flow & Step

JAVA/SpringBatch|2020. 3. 23. 19:41

[I] Flow

  • [C] SimpleFlow
    • [C] JsrFlow

Flow
Batch의 Flow 도메인 클래스이며, 순차 Step 실행에는 Flow가 관여하지 않지만, on 과 같은 더 복잡한 흐름 제어가 필요한 경우 Flow가 필요

  • 메소드
    • FlowExecution start(FlowExecutor) : Flow의 실행을 담당하는 메소드
    • FlowExecution resume(stateName, FlowExecutor) : 특정 State 부터 다시 실행하게 하는 메소드
    • Collection<State> getStates() : Flow에 속한 State를 모두 리턴하는 메소드, State는 handle 메소드를 가지며, FlowExeStatus를 리턴

 

SimpleFlow
종료의 상태는 마지막 State에 의존

  • 변수
    • startState : 시작점 State
    • transitionMap : StateTransition의 Map, Transition을 통해 다음 어떤것을 수행할지 나타낼수 있음
    • StateMap : State에 대한 Map
    • stateTransitions : Transition의 리스트
    • stateTransitionComparator : Transition 비교를 위한 클래스
  • 메소드
    • FlowExecution start(FlowExecutor) : 첫번째 Step부터 실행(resume 호출)
    • FlowExecution resume(stateName, FlowExecutor) : isFlowContinued를 반복해서 호출하며 State를 실행
    • isFlowContinued(State, FlowStatus, StepExe) : State의 상태를 판단하여, Flow를 더 실행할지 제어하는 메소드
    • nextState(stateName, FlowStatus, StepExe) : 다음 State를 구하는 메소드

 

JsrFlow
JSR-352의 로직을 구현한 Flow

 

[I] Step

  • [C] AbstractStep
    • [C] PartitionStep
      • [C] PartitionStep
    • [C] TaskletStep
      • [C] BatchletStep
    • [C] DecisionStep
    • [C] JobStep
    • [C] FlowStep

Step
Step 설정을 나타내는 배치 도메인 인터페이스

  • 메소드
    • isAllowStartIfComplete : Complete 더라도 재실행을 허용할지
    • getStartLimit : 동일 식별자로 실행될수 있는 횟수
    • execute(StepExecution) : Step 의 처리를 다루는 메소드

AbstractStep
Step에 공통처리로직을 담은 AbstractClass

  • 변수
    • CompositeStepExecutionListener : StepExecutionListener를 컴포지트로 가지고 있으며 Step의 선 후 단계에서 호출하는 컴포지트 리스너
    • JobRepository : Job의 메타 정보들을 담당
  • 메소드
    • open(ExecutionContext) : doExecute(stepExe)를 호출하기 전 호출
    • close(ExecutionContext) : doExecute(stepExe) 이후 finally에서 호출
    • [A] doExecute() : 실제 Step 실행을 위해 열어놓은 메소드
    • [A] doExecutionRelease() : doExecute(stepExe) 이후 finally에서 close이후 호출
    • [final] execute(StepExe) : Step에 실행을 다루는 메소드, open, close 및 doExecute()를 실행

PartitionStep
Partition 처리를 위한 Step, 결국 파티셔너를 통해 StepExecutio을 여러개로 만들어서 Executor를 통해 수행
Executor가 기본적으로는 Sync지만, 변경하면 parallel도 가능

  • 변수
    • StepExecutionSplitter : Step을 Split하는 전략을 다루는 클래스, Set split(StepExe, gridSize)
    • PartitionHandler : Collection handle(StepExecutionSplitter,StepExe)
    • StepExecutionAggregator : Aggregate의 전략을 다루는 클래스 aggregate(StepExe, Collection)
  • 메소드
    • doExecute() : TaskExecutorPartitionerHandler 기준으로, executor.execute(task)로 다 돌린 후, stepExeAggregator.aggregate를 통해 aggregate

TaskletStep
간단 실행을 위한 Tasklet을 다루는 TaskletStep, 반복이 가능하며, 각 호출 마다 트랜잭션으로 묶인다.

  • 변수

    • RepeatOperations : Step에 반복 여부를 처리하는 Operations
    • CompositeChunkListener : ChunkListener 들을 컴포지트로 가지고 있는 Listener, chunk 전후에 호출
    • StepInterruptionPolicy : step 호출시마다 종료되었는지를 체크하는 클래스
    • CompositeItemStream : ItemStream을 컴포지트로 가지고있는 클래스, Overide 한 open, close, AbstractStep에 execute()에서
    • PlatformTransactionManager : Step처리에 트랜잭션 제어를 위한 트랜잭션 매니져
    • TransactionAttribute : 에러시 롤백 할지 등의 전략을 제공하는 Attribute
  • 메소드

    • doExecute() : TaskExecutorPartitionerHandler 기준으로, executor.execute(task)로 다 돌린 후, stepExeAggregator.aggregate를 통해 aggregate

DecisionStep
JSR-352에 정의되어있는 DecisionStep이며, JSR-352에 있는것 모두 지원하는 것은 아님

  • 변수

    • Decider : 종료 상태를 결정, String decide(StepExe[])

JobStep
Job을 실행할 수 있도록 하는 Step, 파티셔닝 실행 및 병렬 실행 지원

  • 변수

    • Job : 호출할 Job
    • JobLauncher : Job 실행을 위한 Launcher
    • JobParametersExtractor : JobParam getJobParameters(Job, StepExe) 을 통해 JobParam을 구하는 클래스
  • 메소드

    • doExecute() : jobParam 생성, JobLauncher를 통해 job 실행

FlowStep
Flow 실행을 위한 Step
Step의 그룹핑 실행과 여러 Step들의 파티셔닝 등을 위한 Step
(FlowJob과 거의 코드가 비슷..)

  • 변수

    • Flow : 실행할 Flow
  • 메소드

    • doExecute() : FlowExecutor를 통한 Flow 실행

추후 State, Execution

'JAVA > SpringBatch' 카테고리의 다른 글

[SpringBatch] State  (0) 2020.03.25
[Spring] Spring Batch Reader Writer  (0) 2020.03.24
[Spring Batch] Job  (0) 2020.03.20
[Spring] Spring Batch Tasklet  (0) 2020.02.25
[Spring] Spring Batch Version History  (0) 2020.02.22

댓글()

[Spring Batch] Job

JAVA/SpringBatch|2020. 3. 20. 19:58

다시 Spring Batch를 분석해야할 필요성이 생겨서....
어떤 클래스 구조들을 가지고, 어떤 기능들 및 구현범위들을 제공하고 있는지 살펴보고 있습니다.
물론 일반 개발자들이 Job을 손대거나 커스터마이징 할 일은 잘 없겠지만..

  • [I] Job
    • [C] GroupAwareJob
    • [AC] AbstractJob
      • [C] SimpleJob
      • [C] FlowJob
        • [C] JsrFlowJob

Job
배치에서 Job을 표현하는 가장 상위 도메인 인터페이스, 재시작은 Step 단위가 아니라 Job 단위임을 isRestartable()을 통해 알수 있음

  • getJobParametersValidator() : JobParameter 값의 유효성 체크
  • getJobParametersIncrementer() : Job 실행시 새로운 파라미터를 만들경우(JobParametersIncrementer에 구현 내용은 실제로 JobParam을 받아 JobParam을 리턴하도록 되어있음)
  • isRestartable() : 재시작 여부

GroupAwareJob
배치명을 그룹명을 포함하여 활용할 경우, 발췌잡 -> 론뱅크.발췌잡
그룹명을 들고 있고, 메소드는 다 Job에 있는 것들을 delegate 하여 호출하는 방식


AbstractJob
추상 클래스이며, 공통 의존성들에 대해(JobRepository나 JobExecututionListener나..) 설정들에 대해 로직들이 기술되어있음
실제 대부분 모든 Job은 AbstractJob을 상속받아 구현한 구현체일것
Step 관련된 로직은 대부분 Abstract로 두어 구현한 Job에 따라 원하는 형태로 관리할 수 있도록 함

  • 변수
    • JobRepository : Job의 정보(Param 이나 메타정보)들을 얻거나, 상태를 업데이트 하는 repo
    • CompositeJobExecutionListener : Job 선후에 불릴 JobExecutionListener들을 등록받아 일괄로 불러주는 컴포지트 클래스
    • StepHandler : step의 실제 처리 로직(실행 및 재처리에 따른 처리 및 상태처리 등)을 담고 있는 핸들러
  • 메소드
    • [A] getStep(String) : 추상메소드로 둬서 Step을 어떻게 저장하고 관리할지는 위로 위임
    • [A] getStepNames() : 추상메소드로 둬서 Step을 어떻게 저장하고 관리할지는 위로 위임
    • [final] execute(JobExe) : Job의 메소드이며 핸들러 호출 및 Repo 호출 등에 대한 로직이 담겨 있음, final로 구현 내용을 바꾸지 못하도록 했고, 메소드에서는 doExecute()을 호출하도록 되어있기 때문에 구현 클래스에서는 Job실행은 doExecute()을 통해 구현
    • [final] handleStep(Step, JobExe) : step에 실행에 대한 메소드를 final로 내용을 변경하지 못하도록 했고, StepHandler를 변경함으로 내용을 변경할 수 있도록 제공
    • [A] doExecute(JobExe) : 구현 클래스에서 Job 실행 부분을 구현하도록 열어놓은 메소드

SimpleJob
Step을 순차적으로 실행하는 Job의 구현체
Step이 실패시 Job이 실패하며, 모든 Step이 Complete 될경우 Job이 Complete 된다.

  • 변수
    • ArrayList : Step을 ArrayList로 관리//Step이 그렇게 많지는 않겠지만, getStep은 O(n)
  • 메소드
    • doExecute(JobExe) : step을 handleStep()으로 호출, Completed가 아닐시 break

FlowJob
순차실행 보다는 Flow를 통한 복잡한 처리를 위한 JobClass
초기 작업에서(findSteps) Flow에 있는 Step들을 stepMap에 넣고 시작

  • 변수
    • Flow : 실행할 Flow, 내부에 여러 Step이 존재
    • Map<String,Step> : Flow내에 존재하는 Step을 파싱(findSteps())하여 저장
  • 메소드
    • findSteps(Flow,Map) : Flow에서 Step들의 정보들을 꺼내서 Map에 저장
    • doExecute(JobExe) : flow.start(FlowExecutor)

JsrFlowJob
FlowJob을 상속 JSR-352 명세에 FlowJob

'JAVA > SpringBatch' 카테고리의 다른 글

[SpringBatch] State  (0) 2020.03.25
[Spring] Spring Batch Reader Writer  (0) 2020.03.24
[Spring Batch] Flow & Step  (0) 2020.03.23
[Spring] Spring Batch Tasklet  (0) 2020.02.25
[Spring] Spring Batch Version History  (0) 2020.02.22

댓글()

[Spring] Spring Batch Tasklet

JAVA/SpringBatch|2020. 2. 25. 20:07

ETL이나 각종 기능들은 결국 Tasklet을 구현하여 제공하는 기능들이며

Tasklet은 execute(S,C) 메소드 만을 제공합니다.

 

/**
* Given the current context in the form of a step contribution, do whatever
* is necessary to process this unit inside a transaction. Implementations
* return {@link RepeatStatus#FINISHED} if finished. If not they return
* {@link RepeatStatus#CONTINUABLE}. On failure throws an exception.
* 
* @param contribution mutable state to be passed back to update the current
* step execution
* @param chunkContext attributes shared between invocations but not between
* restarts
* @return an {@link RepeatStatus} indicating whether processing is
* continuable. Returning {@code null} is interpreted as {@link RepeatStatus#FINISHED}
*
* @throws Exception thrown if error occurs during execution.
*/
@Nullable
RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception;

결국 리턴이 RepeatStatus.FINISHED(혹은 null) 로 리턴되면 마치게 되고 RepeatStatus.CONTINUABLE 의 경우에는 execute를 다시 호출하게 됩니다

(리턴값을 RepeatStatus.CONTINUABLE로 계속 반환하면 무한히 돌겠죠..)

 

 

Spring Batch에서 Tasklet을 imple하여 제공하고 있는 클래스 및 interface는 아래와 같습니다.

 

  • [I] Tasklet
    • [C] MethodInvokingTaskletAdapter : POJO 메소드 호출을 Step 시점에 호출하기위한 wraps 클래스
    • [C] CallableTaskletAdapter : Callable을 Step 시점에 호출하기 위한 wraps 클래스
    • [C] ChunkOrientedTasklet : ChunkProvider(SimpleChunkProvier 기준으로 ItemReader) , ChunkProcessor(SimpleChunkProcessor 기준으로 ItemProcessor, ItemWriter)를 활용하는 Tasklet(ETL)
    • [I] StoppableTasklet : (3.0부터) stop() 메소드를 구현하도록 하는 인터페이스며, 프레임워크에서 JobOperator.stop 시 해당 메소드를 불러줍니다.
      • [C] BatchletAdapter : (3.0부터) Batchlet을 지원하는 Tasklet Batchlet은 arg가 없는 process와 stop 메소드가 있는 interface 입니다.
      • [C] SystemCommandTasklet : Command(Java가 아닌 별도 프로그램을 실행한다던지)를 위한 Tasklet

 

 

'JAVA > SpringBatch' 카테고리의 다른 글

[SpringBatch] State  (0) 2020.03.25
[Spring] Spring Batch Reader Writer  (0) 2020.03.24
[Spring Batch] Flow & Step  (0) 2020.03.23
[Spring Batch] Job  (0) 2020.03.20
[Spring] Spring Batch Version History  (0) 2020.02.22

댓글()

[Spring] Spring Batch Version History

JAVA/SpringBatch|2020. 2. 22. 19:39

https://docs.spring.io/spring-batch/docs/3.0.9.RELEASE/reference/html/whatsNew.html

https://docs.spring.io/spring-batch/docs/4.2.x/reference/html/whatsnew.html#whatsNew

추후 각 버전별 주요 사항들을 조금씩 정리해보려고 합니다.

'JAVA > SpringBatch' 카테고리의 다른 글

[SpringBatch] State  (0) 2020.03.25
[Spring] Spring Batch Reader Writer  (0) 2020.03.24
[Spring Batch] Flow & Step  (0) 2020.03.23
[Spring Batch] Job  (0) 2020.03.20
[Spring] Spring Batch Tasklet  (0) 2020.02.25

댓글()

[MSA] sidecar 패턴

JAVA/Spring|2020. 1. 13. 19:41

개인적으로 개발할때는 Spring만 사용해왔기 때문에 Sprin Cloud는 살펴보곤 했지만

폴리글랏은 고려하지 않았기 때문에 다른것들은 살피지 않았습니다.

 

하지만, 최근에 회사에서 istio 라는 서비스 매쉬 패턴을 구현한 시스템? 을 살펴볼일이 있었습니다.

 

해당 시스템은 폴리글랏을 지원하기 위하여 각각의 언어별로 라이브러리를 제공하는 형식이 아닌

SideCar 패턴(Cloud 기능을 갖은 프로세스이며, Proxy 역할을 하는 프로세스)을 통해 Cloud 기능들을 언어 상관없이

지원하는 방향으로 설계 된것을 살펴보며 

자바에 거의 한정된 netflix oss가 아닌 istio가 인기있을만하다는 생각을 하며

 

그렇다면 "netflix oss에는 sidecar 패턴 구현체가 없나? 아니면 고려한 부분이 없나?"라는 생각으로 검색을 해보았습니다.

(필요시 없으면 그냥 SpirngBoot App 하나로 Proxy 형식으로 하나 만들면 되겠다는 생각도 하기도 했습니다)

 

그런데... 역시 있군요..

https://cloud.spring.io/spring-cloud-netflix/multi/multi__polyglot_support_with_sidecar.html

 

 

9. Polyglot support with Sidecar

9. Polyglot support with Sidecar Do you have non-JVM languages with which you want to take advantage of Eureka, Ribbon, and Config Server? The Spring Cloud Netflix Sidecar was inspired by Netflix Prana. It includes an HTTP API to get all of the instances (

cloud.spring.io

신기술 마냥 이제서야 접했지만 역시 세상은 넓다는걸 경험했습니다..;;

 

추후 istio관련 이야기가 지속된다면 각각 학습한 내용? 정리할 내용들을 시간이 되면 포스팅할것 같습니다

 

'JAVA > Spring' 카테고리의 다른 글

[JPA] LockType  (0) 2020.07.23
[Spring] LifeCycle, SmartLifeCycle  (0) 2020.06.23
[SpringConfig] Properties 암호화  (0) 2019.12.24
spring boot log level 변경(actuator)  (0) 2019.12.19
reactor Schedulers  (0) 2019.12.16

댓글()

java.util.function 인터페이스

JAVA|2019. 12. 30. 19:24

함수 참조시 주로 나오는 function type

중요 인터페이스 6가지

  • UnaryOperator

    • 받은 타입 그대로 리턴
    • ex) String.trim
  • BinaryOperator

    • 받은타입 그대로 리턴 하나, 인자가 두개
    • ex) Integer.add
  • Predicate

    • 인자를 받아, boolean을 리턴
    • ex) Strings.isEmpty
  • Function<T,R>

    • 인자 타입과 리턴타입이 다를경우
    • ex) List.get
  • Supplier

    • 인자는 없고, 리턴만 있는경우
    • ex) List.size
  • Consumer

    • 인자는 있고, 리턴은 없는경우
    • ex) System.out.println

    다 제네릭을 사용하고 있어서 primitive 타입을 바로 활용하기 어려워 보이지만
    primitive를 활용하기 위해서 별도의 인터페이스들을 제공합니다.
    예) UnaryOperator 에서 int를 사용하기 위해서는 IntUnaryOperator
    예) Predicate 에서 long를 사용하기 위해서는 LongPredicate

'JAVA' 카테고리의 다른 글

Java Time  (0) 2020.07.06
SortedQueue...  (0) 2020.07.02
JEP 218: Generics over Primitive Types  (0) 2019.12.10
[CompletableFuture][#3] 메소드 정리-1  (0) 2019.09.01
[Quartz] Trigger  (0) 2019.07.10

댓글()