paint-brush
París markat Berlín markar: Kunjamas Kotlin markanx interruptores ukanakax lurasispaukata@jesperancinha
420 ullart’awinaka
420 ullart’awinaka

París markat Berlín markar: Kunjamas Kotlin markanx interruptores ukanakax lurasispa

ukata João Esperancinha26m2025/01/23
Read on Terminal Reader

Sinti jaya pachanakawa; Uñxatt’añataki

Jichhürunakanx interruptores ukanakax apnaqatawa, ukhamat mä jan ukax yaqha jan jaysir servicio ukar jan sinti mayiwinak lurañataki. Kunawsatix sañäni mä serviciox jist’antatäki ukhax kunatsa, mä interruptor de circuito ukax kunjamtix sutipax siski ukhamarjamaw circuito p’akjañapa. Aka qillqatanxa, kimsa programaticamente uñakipañäni, interruptores ukanaka phuqhañataki, mä AOP ukan phuqhawimpi.
featured image - París markat Berlín markar: Kunjamas Kotlin markanx interruptores ukanakax lurasispa
João Esperancinha HackerNoon profile picture
0-item

1. Uñt’ayañataki

Jichhürunakanx Circuit-breakers apnaqatawa, ukhamat jan sinti mayiwinakax mä jan ukax yaqha servicio jan jaysañataki. Amuytʼañataki, kunapachatï mä serviciojj jistʼantatäki ukhajja, kunatsa mä interruptorajj kunjamtï sutipajj siski ukhamarjamaw circuito pʼakjañapa. Mä arunxa, mä situación ukanx 1 millón mayiwinakaw mä pachan lurasiski, mä caballot t’ijtäwin askinak jikxatañataki, uka mayiwinakax yaqha servicio ukar kutt’ayañ munapxta, ukax ukax apnaqañapawa.


Aka yaqha servicio ukaxa mä réplica ukhamawa, jan ukaxa purapata apnaqatarakiwa yaqha lurawinakaru lurañataki original servicio ukan jan walt’awipata. Tukuyañ amtax sapa kutiw jan wakiskir jawsatanakar t’unjañawa ukat yaqha chiqan flujo ukax irpañawa. 2017 maranx , Michael Nygard Circuit Breaker ukan diseño ukan patrón ukarux software desarrollo ukan diseño ukan nayrar sartayawayiwa. Ukax Release It!: Diseño y Despliegue de Software Listo para la Producción (Programadores Pragmáticos) 1ra Edición ukan qillqatapan lurasiwayi.


Uka patrón de diseño circuit breaker chiqpach circuitos electrónicos ukat eléctricos ukanakat amuyt’ayatawa. Ukampirus mä jach’a amuyunakatxa, chiqpachansa interruptor de circuito uka amuyunakax 1879 maran Thomas Edison jupaw uñstayatayna . Kunjamtï uka tiempon luraskäna ukhamarakiw mä corriente phuqhantat uñjasiñapa. Wali, wali sapuru arunakampixa, akax arquitectura de software ukaruw aka tuqinx apnaqasktanxa. Jilïr amtax sistema ukax wali ch’amampiw ch’amanchasi. Kunjams resiliente ukhamarak kunjams fault-tolerant ukax chiqpachapuniw ingenieronakan nayraqatapanx aka patrón phuqhañ yanapt’añataki. Uka amuyux akawa , yaqhip condicionanakanx mä mayiwix jan kuna jan walt'awimpiw yaqha juk'amp utjki uka flujo ukar pachpa endpoint qhipäxanx mayjt'ayañ munaraksna .


A ukat B ukar mä mayiw phuqhañ munapxta sañäni. Awisax B ukax pantjasiwa ukatx C ukax sapa kutiw utji. B ukax aleatoriamente pantjasispa ukhaxa, C ukaruw puriñ munapxta, ukhamat servicios ukanakax taqpach utjañapataki. Ukampirus B ukar kutt’ayañ mayiwinak lurañatakix, B ukax jan mayamp ukham pantjasiñapatakiw uñjañ munapxta. Ukatx sistema ukarux configurar luraraksnawa, B ukar aleatorio mayiwinak lurañataki ukat B ukar taqpach kutt’añatakikix mä kutix tasa de fallo ukax mä nivel ukar sarawayxi ukhakiw.


Inas C mayiwix pantjasiwi tuqit lurañ munstan ukampis latencia tuqit lurañ munaraksnawa. B ukax wali llamp’u chuymanïchi ukhaxa, inas taqi mayiwinak C ukar wasitat apayañ munaraksna. Walja yaqha configuración ukanakaw utji, kunjamatix C uksar puriñ yant’añax mä qhanañchat jakhüwi yant’awinak tukuyatat, mayiwi kasta, concurrentes hilos, ukat walja yaqha amtawinakax Akax uñt’atarakiwa short-circuiting , ukatx jilpachax mä juk’a pachatakiw sarnaqawi.

Maquina Estatal ukaxa


Kunas chiqpachanx mä interruptor ukax uk juk’amp amuyañatakix, mä interruptor de circuito ukax mä entidad ukhamaw jiwasan aplicación ukanx irnaqaski, uk amuyañasawa. Mä circuito-interruptor ukan kimsa jach’a estados ukanakaw utji. Ukax jist’antatäspawa, jist’aratäspawa, jan ukax chikat jist’aratäspawa. Mä estado jist’antat ukax jiwasan aplicación flujos normales ukan sarnaqañ sañ muni. Jiwasax jan kuna usuniw A servicio ukar mayiwinak luraraksna, taqi mayiwinakax servicio B ukar sarañ yatisax Estado abierto ukax sañ muniw taqi mayiwinakax servicio B ukarux jan phuqhasiñapataki. Mä pantjasiw uñacht’ayañatakix kamachinak uñt’ayawayktan ukax utjawayiwa ukatx janiw servicio B ukaruw puriñjamakiti, aka tuqinx mä excepción ukax sapa kutiw kutt’ayataraki. Estado half-open ukax kunapachatix jiwasan interruptor ukarux servicio B ukan yant’äwinak lurañapatak yatiyatäki ukhax wasitat irnaqaskiti janicha uk yatiñataki.


Sapa mayt’awix suma phuqhaski ukax normal ukhamaw uñjasi, ukampis C ukarux mayiwinak luraskakiniwa, B ukax kunjamtix suyatäki ukhamarjam sarnaqaspa ukhax jiwasan utt’ayat kamachinak chiqanchañ kamachirjama, jiwasan interruptor de circuito ukax jist’antat estado ukar kutt’ani, ukatx servicio A ukax lurañ qalltani solicitudes exclusivamente a servicio B. Jilapacha apnaqawinakanxa, mä interruptor de circuito ukaxa decorador diseño patrón ukarjamawa. Ukampirus amparampi phuqhasispawa, ukatx kimsa programatico thakhinak uñakipt’añäni, interruptores de circuito ukar phuqhañataki, ukatx tukuyañatakix AOP ukan phuqhasiñapatakiw uñakipt’añäni. Uka chimpux GitHub ukan uñt'ayatawa.

Uñacht’äwi

2. Auto Checks ukanaka

Aka yatichäwin qhipa tʼaqapanxa, auto tʼijuñ anattʼañ tuqitwa uñakiptʼañäni. Ukampirus janïr uka chiqar puriñkamax mä qawqha askinak mä aplicación lurañatakix mä circuit breaker ukamp irnaqañapatak irpañ munapxsma .

2.1.1.1. Kystrix (parís-at-berlín-kystrix-runable-app) ukax mä jach’a uñacht’äwiwa.

Kystrixs , mä jisk'a DSL ukhama , mä muspharkañ biblioteca ukaw Johan Haleby jupan uñstayata ukat lurata . Biblioteca ukax walja lurañanak churaraki, Spring ukat Spring WebFlux ukanakamp mayachasiñataki. Mä uñakipañax wali askiwa ukat mä juk’a anatt’añax wali askiwa:

 <dependency> <groupId>se.haleby.kystrix</groupId> <artifactId>kystrix-core</artifactId> </dependency> <dependency> <groupId>se.haleby.kystrix</groupId> <artifactId>kystrix-spring</artifactId> </dependency>


Nayax mä uñacht’äw lurawayta, ukatx ukax módulo from-paris-to-berlin-kystrix-runnable-app GitHub ukan jikxatasi. Nayraqatxa, aka chimpunak uñakipt’añäni:

 @GetMapping("/{id}") private fun getCars(@PathVariable id: Int): Mono<Car> { return if (id == 1) Mono.just(Car("Jaguar")) else { hystrixObservableCommand<Car> { groupKey("Test2") commandKey("Test-Command2") monoCommand { webClient.get().uri("/cars/carros/1").retrieve().bodyToMono<Car>() .delayElement(Duration.ofSeconds(1)) } commandProperties { withRequestLogEnabled(true) withExecutionTimeoutInMilliseconds(5000) withExecutionTimeoutEnabled(true) withFallbackEnabled(true) withCircuitBreakerEnabled(false) withCircuitBreakerForceClosed(true) } fallback { Observable.just(Car("Tank1")) } }.toMono() } }

Aka chimpuxa uñacht’awina 2 kamachi uñacht’ayi. Kamachi 1. Kunatix akanx luraski ukax monoCommand ukampiw munat kamachir qhanañchasktanxa. Aka chiqanx, kuna thakhis jawsañax wakisi uk qhanañcht’apxtanwa. commandProperties ukanxa, kamachinakaxa qhananchatawa kunatixa circuit-breaker mayjt’ayaña estado jist’arañataki. Jiwasax qhanpach jawsañasarux qhiphart’ayapxtanwa, ukhamat 1 segundo chiqaparu puriñapataki.


Uka pachparaki, 5000 milisegundos ukja pacha tukuyaña uñt’ayaraktanxa. Ukax sañ muniwa, janipuniw mä tiempo de espera ukar puriñäniti. Aka uñacht’awina, mä Id ukampiw jawsañanak lursna. Niyakixay akax mä yant’awikïchixa, Id=1 , mä auton Id ukhamaw sasaw amuyapxtanxa, mä Jaguar ukax janiw circuit-breaker ukax wakiskiti . Ukax sañ munarakiw janipuniw Tank1 ukax jikxataskaniti kunjamtix fallback método ukan qhanañchaski ukhama. Janitï jichhakamax amuyasksta ukhaxa, fallback método ukar sum uñakiptʼañamawa. Aka lurawix mä Observable ukampiw apnaqasi. WebFlux ukax Observable ukan diseño ukarjam phuqhachatäkchisa, Flux ukax janiw chiqpachans Observable ukhamäkiti.


Ukampirus, hystrix ukax panpachaniw yanapt’i. Mä aplicación ukar apnaqañamawa, ukatx navegador ukar jist’arañamawa http://localhost:8080/cars/2 , ukax chiqañchañataki. Wali askiw amuyañaxa, jumatix wali nayratpach jawsañ qalltasma Spring Boot qalltawinxa, inas qhipharux mä Tank1 yatiyaw katuqaraksta. Ukax kunatix qalltañ qhipharux 5 segundos ukjat jilaw wali jasakiw kunjams aka lurawix apnaqasi ukarjamaw lurasispa. Payïr uñacht’äwinx, jiwasan uñacht’äwisarux Tanque 2 ukar cortocircuito ukamp uñacht’ayañani:

 @GetMapping("/timeout/{id}") private fun getCarsTimeout(@PathVariable id: Int): Mono<Car> { return if (id == 1) Mono.just(Car("Jaguar")) else { hystrixObservableCommand<Car> { groupKey("Test3") commandKey("Test-Command3") monoCommand { webClient.get().uri("/cars/carros/1").retrieve().bodyToMono<Car>() .delayElement(Duration.ofSeconds(1)) } commandProperties { withRequestLogEnabled(true) withExecutionIsolationThreadInterruptOnTimeout(true) withExecutionTimeoutInMilliseconds(500) withExecutionTimeoutEnabled(true) withFallbackEnabled(true) withCircuitBreakerEnabled(false) withCircuitBreakerForceClosed(true) } fallback { Observable.just(Car("Tank2")) } }.toMono() } }

Aka uñacht’awina, jiwasana circuit-breaker ukaxa mä estado abierto final retorno Tanque 2 ukarux mä jaysawimpiw sarani. Ukax kunatix jiwasax mä 1s qhipharäwiw akanx luraraktanxa, ukampis jiwasan condición de ruptura de circuito ukax 500ms markan qhipatw ch’amanchasi sasaw qhanañchapxta. Jumatix yatiskta kunjams hystrix irnaqaski, ukax jikxatasmawa kystrix ukax janiw kunas mayjäkiti nayrar sartañataki. Kuntix hystrix ukax jan aka pachanx nayatak churawaykitu, mä jan ch’am tukus, jan ch’am tukus kuntix nayax anatäw lurañatakix wakiski uk churañataki. Kystrix jupax mä cliente ukarjam irnaqkaspas ukhamawa. Ukax sañ muniw jiwasan código ukar yatiyañasawa janïr servicios ukanakar mayiwinak lurañkamax jiwasan jach’a servicio qhipäxanxa.

2.2.2.2.1. Resiliencia ukaxa4J

Resilience4J ukax waljaniruw uñt’ayasi, mä interruptor ukan wali phuqhat phuqhawipa. Nayrïr yant’äwinakajax interruptores ukan yaqhip wakiskir tuqinakat yatxatañatakiw sarawayta. Mä arunxa, mä interruptor uñjañ munta, ukax tiempo de espera ukat sapa kuti sum mayitanakarjamaw irnaqaspa. Resilience4J ukaxa kunaymana kasta módulos de short-circuiting wakicht’añatakixa jay satawa. Ukanakax 6 kunayman jamuqanakaruw jaljasi: CircuitBreaker , Bulkhead , Ratelimiter , Retry , ukat Timelimiter . Taqi ukanakax patrón de diseño ukan sutinakaparakiwa. CircuitBreaker uka módulo ukax aka patrón ukan taqpach phuqhawip uñacht’ayi.


Jiwasax walja parámetros ukaniwa configurar, ukampis esencial, módulo CircuitBreaker ukax configurar kuntix uñt’ktan ukax mä fallo ukhama, qawqha mayiwinaks permitimos estado chika jist’arat ukhamarak mä ventana deslizante, ukax configurar tiempo jan ukax jakthapiwi, kawkhantixa mayiwinaka jakthapiwixa jist’antata estado ukana utji. Ukax pantjasiwinak sapa kuti jakhthapiñatakix wali askiwa. Chiqpachanx aka CircuitBreaker módulo ukax tasa de solicitud ukampiw yanapt’istani sañjamawa, ukampis ukax janiw chiqäkiti.


Kunjamsa qhanañchäta ukarjamaw lurasini. Pantjasiwinakar saykatañatakik amuytʼañax jukʼamp askïkaspas ukhamawa. Mä pacha tukuyatat jutapxchi jan ukax mä excepción ukan jutapxchi, akax kawkhantix uñjatäki ukat kunjams mayiwinakax jan kuna jan walt’awimp yaqha chiqar mayjt’ayatäspa Módulo Bulkhead ukax mä pachan mayiwinakar uñjañatakiwa. Janiw mä tarifa limitador ukhamäkiti.


Ukhamakipansti, ukax patrón de diseño de Bulkhead ukaruw phuqhi, ukax mä sapa tukuyan jan sinti lurañanak utjañapatakiw apnaqasi. Ukhamächi ukhaxa, Bulkhead mayiwinakas mä thakhinjam lurañ yanapt’istu, ukhamat taqi utjki uka tukuyañ chiqanakan jaljatäñapataki. Bulkhead sutix kunayman sellado compartimientos ukanakat juti, mä jach’a barcox jan chhaqhañapataki, mä accidente utjaspa ukhaxa, ukat kunjamatix barconakax utjki ukhamarakiw qawqha hilos ukanakax piscina de hilos ukan utjani ukat arrendamiento ukan pachap qhanañchañasa .


RateLimiter uka módulo ukax tasa de solicitud ukar uñjañatakiwa. Aka ukat módulo Bulkhead ukan mayjt’awipax wali wakiskiriwa kunatix jiwasax tasas ukar tolerante ukhamäñ munapxta mä puntokama. Ukax sañ muniw janiw ukatakix pantjasiwinak utjayañax wakiskiti. Jiwasax ukhamakiw sañ munapxta, diseño ukanx janiw mä tasa mä valor ukar juk’amp tolerañjamäkiti. Ukhamaraki, mä mayiwiruw mayjt’ayaraksna jan ukax mayiwi phuqhañatak permiso churañkamax suyt’ayaraksnawa. Retry uka módulo ukax inas juk’amp jasakiw amuyañax kunatix janiw yaqha módulos ukanakamp chikachasiñax utjkiti.


Jiwasax chiqpachanx qhanancht’tanwa qawqha kutis yant’awinakax utji mä tukuyar puriñkama, jiwasan umbral definido ukar puriñkama. Módulo Timelimiter ukax mä simplificación ukhamaw uñjasispa CircuitBreaker uka módulo ukax panpachaniw configurar tiempos de espera ukar uñt’ayasipxi. Ukampirus Timelimiter janiw yaqha parámetros ukanakat dependerkiti kunjamakitix ventanas deslizantes ukanakax ukhamarakiw jan mä calculación umbral de fallo in-build ukankiti.


Ukhama, jiwasatix mä servicio ukar jawskasax tiempos de esperas ukar q’umachañ munstanxa, ukat yaqha pantjasiwinak jan factor ukarjam uñjksna ukhax Timelimiter ukampix juk’amp askïspawa.

2.2.1.1.1.1. Resilience4J ukax Kotlin ukat No Spring uka marco ukampiw (parís-at-berlín-resilience4j-runnable-app)

Aka módulo ukanx resilience4j kotlin biblioteca ukak apnaqañ amtawayta:

 <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-kotlin</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-retry</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-circuitbreaker</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-ratelimiter</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-timelimiter</artifactId> </dependency>


Aka phuqhawix repo ukan GitHub ukan uñt’ayatawa. Nayraqatax TimeLimiter ukan uñacht’äwip uñakipt’añäni:

 var timeLimiterConfig: TimeLimiterConfig = TimeLimiterConfig.custom() .timeoutDuration(Duration.ofMillis(100)) .build() var timeLimiter: TimeLimiter = TimeLimiter.of("backendName", timeLimiterConfig) private suspend fun getPublicCar(): Car { return timeLimiter.decorateSuspendFunction { getPrivateCar() }.let { suspendFunction -> try { suspendFunction() } catch (exception: Exception) { Car("Opel Corsa") } } } private suspend fun getPrivateCar(): Car { delay(10000) return Car("Lancya") }

Uka tuqinxa, jiwasan function getPrivateCar ukax TimeLimiter lurawimpiw k’achacht’atäski decorateSuspendFunction lurawimpi. Kuntix akax lurani ukax mä tiempo de espera ukaw utjañapa, función ukar jawsktan ukax sinti jaya pachaw mä Opel Corsa ukax Lancya ukat sipanx jikxatasi. Uk yant’añatakix, ukak apnaqañasawa ukat http://localhost:8080/cars/timelimiter/normal/1 uk jist’araraksnawa.


Uka phuqhawi uñakipt’asax uñjtanwa, janipuniw mä Lancya ukax jikxataskaspati. Ukat ukax kunatix amuyuparjamaw 10s suyt’apxta janïr kutt’ayañkama. Jiwasan TimeLimiter ukax mä juk’a pachakiw utji ukhamat akax janipuniw irnaqkaniti. Mä TimeLimiter ukax mä juk’a amuyañjamawa. Maysa tuqitxa, CircuitBreaker , ukax yaqha sarnaqäwiwa. Akax mä uñacht’äwiwa kunjams ukax lurasispa:

 val circuitBreakerConfig = CircuitBreakerConfig.custom() .failureRateThreshold(20f) .slowCallRateThreshold(50f) .slowCallDurationThreshold(Duration.ofMillis(1000)) .waitDurationInOpenState(Duration.ofMillis(1000)) .maxWaitDurationInHalfOpenState(Duration.ofMillis(1000)) .permittedNumberOfCallsInHalfOpenState(500) .minimumNumberOfCalls(2) .slidingWindowSize(2) .slidingWindowType(COUNT_BASED) .build() val circuitBreaker = CircuitBreakerRegistry.of(circuitBreakerConfig).circuitBreaker("TEST") private suspend fun getPublicCar(id: Long): Car { return circuitBreaker.decorateSuspendFunction { getPrivateCar(id) }.let { suspendFunction -> try { suspendFunction() } catch (exception: Exception) { Car("Opel Corsa") } } } private fun getPrivateCar(id: Long): Car { if (id == 2L) { throw RuntimeException() } return Car("Lancya") }

Uka tuqinxa, jiwasaxa sañ munapxtanwa jiwasana interruptor ukaxa circuito jist’antañapawa mä kuti tasa de falla ukaxa 20% ukjata jisk’akiwa propiedad ukampi. K’achat k’achat jawsatanakax mä umbral ukanirakiwa, ukampis aka tuqinx 50% ukjat juk’ampikiw utjani. Mä k’achat jawsañax 1s ukjat juk’amp pachaw utjañapa sasaw sapxtanxa, ukhamat mä jawsatäñapataki. Ukhamaraki, chika jist’arat estado ukan pachapax 1s ukhamäñapawa sasaw qhanañcharaktanxa. Ukax sañ muniw, chiqpachanx estado abierto, estado medio abierto, jan ukax estado cerrado ukanïñäniwa.


Ukhamaraki sapxaraktwa, mä máximo 500 chika jist’arat estado mayiwinakarux jaysapxtanwa. Pantjasiwi jakthapiwinakatakixa, interruptor ukaxa kawkiri markansa ukham lurani uk yatiñapawa. Ukajj kunapachas circuito jistʼantañasa uk yatiñatakejj wali wakiskiriwa. Jiwasax siwa 2 mayiwix juk’akiw aka jakhüwitakix wakisini, ukax propiedad minimumNumberOfCalls ukampi. ¿Amtastati chikat jist’arat ukax kunapachatix circuito jist’antañatak ch’amachasiskakiñäni, mayiwinakax mä seguro umbral de fallo ukar purispa ukhaxa?


Aka configuración ukanxa, sañ muniwa 2 mayiwi lurañasa wakisi, ventana deslizante ukanxa, frecuencia de error ukanaka jakhthapiñataki ukhamaraki estado cerrado ukar kutt’añatakisa jani ukaxa jani utjañapataki. Akax taqi variables ukanakan chiqaparu uñakipañawa. Taqi kunat sipansa, kuntix ukax sañ munki ukax jiwasan aplicación ukax walja jawsatanakaw servicio alternativo ukar luraspa, utjaspa ukhax janiw sinti jasakix estados abierto ukanakat jist’antat ukar mayjt’kaniti kunatix tasa de éxito ukax lurañatakix 80% chikat pachanx utjañapawa -jist’arat estados ukat jist’arat estado ukatakix pacha tukuyañax utjañapawa.


Ukham pachanak uñt’ayañatakix walja thakhiw utji. Jiwasan uñacht’awisanx maxDurationInHalfOpenState ukax 1s ukhamawa sasaw sapxtanxa. Ukax sañ muniw jiwasan CircuitBreaker ukax estado jist’arat uñjani, ukax jiwasan chequeo ukax janiw condición de estado jist’antat ukar phuqhkiti jan ukax aka tiempo de espera ukax janïraw utjkiti. Aka CircuitBreaker ukan qhanañchata sarnaqawix inas ch’amakïchispa arktañataki ukhamarak yatiyañataki, q’uma kunatix específicos tiempos de inactividad, tasas ukat yaqha lurawinakat mayiwinakax mäkiw jan chiqapar uñtasit lurañax wakiskiti, ukampis walja mayiwinak aka tukuyar lurañäni ukhax uk uñjañäni uka sarnaqawix akham uñacht’ayatawa, jiwasan experienciasampi chika.


Ukhama, yant’añäni ukat walja mayiwinak tukuyañ chiqanakar phuqhañäni: http://localhost:8080/cars/circuit/1 ukat http://localhost:8080/cars/circuit/2 . 1 ukampi tukuyañax mä suma auto apsuñ tukuyañawa, ukatx 2 ukampi tukuyañax mä especificado auto katuqañan jan walt’awipawa. Código uñakipt’asax uñjtanwa, kunatix 2 ukat sipanx mä Lancya ukax mä jaysäwiw sañ muni. A 2 , ukax sañ muniw jank’akiw mä excepción de tiempo de ejecución ukar jaquntañasa, ukax sañ muniw mä Opel Corsa ukar jaysañatak tukuyañasa.


Jiwasatix 1 tukuyäwir mayiwinakak lurañänixa, Lancya mä jaysäwimp uñjaskakiñäniwa. Sistema ukax jan walt’ayañ qalltxi ukhaxa, ukax 2,\; uñjätawa Lancya markar kutt’añax janiw mä juk’a pachatxa constante ukhamäkaniti. System ukax estado Abierto ukankatapat yatiyani, ukatx janiw juk’amp mayiwinakax jaysatäkiti.

 2021-10-20 09:56:50.492 ERROR 34064 --- [ctor-http-nio-2] .fcbrrcCarControllerCircuitBreaker : io.github.resilience4j.circuitbreaker.CallNotPermittedException: CircuitBreaker 'TEST' is OPEN and does not permit further calls


Ukatx jiwasan interruptor de circuito ukax chika jist’arat estado ukar sarani mä suma mayiwi tukuyatatxa, ukat ukax sañ muniw mä qawqha mayiwinak 1 ukar kutt’ayañax wakisispa janïr normalizatäkipana. Mä pä kutiw Lancya markat Opel Corsa markar mayjt’ayañäni, janïr Lancya ukar wasitat puriñkama. Aka jakhüwix 2. Akax pantjasiw jakhüwitakix jisk’akiwa. Jiwasatix mä pantjasiwiruki lurasktan ukat jan pantjasir tukuyañ chiqar jawsaskakiñäni ukhaxa, kunatix luraski ukanak juk’amp qhan uñacht’ayaraksnawa:

 2021-10-20 11:53:29.058 ERROR 34090 --- [ctor-http-nio-4] .fcbrrcCarControllerCircuitBreaker : java.lang.RuntimeException 2021-10-20 11:53:41.102 ERROR 34090 --- [ctor-http-nio-4] .fcbrrcCarControllerCircuitBreaker : io.github.resilience4j.circuitbreaker.CallNotPermittedException: CircuitBreaker 'TEST' is OPEN and does not permit further calls

Aka jist’arat estado yatiyawix chiqäkchisa, 2 mayiwinak jan pantjasir tukuyañ chiqar lurawaykta uka qhipatw uñstawayi. Ukatpï estadox chikat jist’aratawa sasaw sapxi.

2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.1. Resilience4J ukax Spring Boot ukampiw ukat No AOP ukampiw (parís-at-berlín-resilience4j-primavera-app)

Nayrir t’aqapanx kunjams mä jach’a programatjam phuqhañax uk uñjapxta, jan kuna tecnología Primavera apnaqasa. Jiwasax Spring uka apnaqapxta ukampis mä WebFlux MVC tipo de servicio ukak churañataki. Ukhamarus, janiw kuns mayjt’ayawaykti servicios ukanakat pachpa. Aka aplicación ukanx aka bibliotecas ukanakat yatxatañäni:

 <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot2</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-all</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-reactor</artifactId> </dependency>


Kunjams codigox lurasi uk uñakipt’asax mä jach’a mayjt’äwiw uñjasi:

 @RestController @RequestMapping("/cars") class CarController( private val carService: CarService, timeLimiterRegistry: TimeLimiterRegistry, circuitBreakerRegistry: CircuitBreakerRegistry, bulkheadRegistry: BulkheadRegistry ) { private var timeLimiter: TimeLimiter = timeLimiterRegistry.timeLimiter(CARS) private var circuitBreaker = circuitBreakerRegistry.circuitBreaker(CARS) private var bulkhead = bulkheadRegistry.bulkhead(CARS) @GetMapping("/{id}") private fun getCars(@PathVariable id: Int): Mono<Car> { return carService.getCar() .transform(TimeLimiterOperator.of(timeLimiter)) .transform(CircuitBreakerOperator.of(circuitBreaker)) .transform(BulkheadOperator.of(bulkhead)) .onErrorResume(TimeoutException::class.java, ::fallback) } @GetMapping("/test/{id}") private fun getCarsTest(@PathVariable id: Int): Mono<Car> { return carService.getCar() .transform(TimeLimiterOperator.of(timeLimiter)) .transform(CircuitBreakerOperator.of(circuitBreaker)) .transform(BulkheadOperator.of(bulkhead)) .onErrorResume(TimeoutException::class.java, ::fallback) } @GetMapping("/carros/{id}") private fun getCarros(@PathVariable id: Long): Mono<Car> { return Mono.just(Car("Laborghini")) } private fun fallback(ex: Throwable): Mono<Car> { return Mono.just(Car("Rolls Royce")) } }

Aka uñacht’awina ukhamaraki aka uñacht’awina, jilpachaxa propiedades de tiempo de espera ukanakat uñakipt’añäni. CircuitBreaker ukan jan walt’awinakapax jupanakpachaw juk’amp jan wakiskirïkiti kunatix akax mä uñt’ayawiwa. Kunatix akan amuyañax wali wakiskirïki ukax kunjams jasakiw ukax phuqhassna decoradores ukanakamp churat Spring by Resilience4J . Wali programmatical ukhamäkchisa, qallta yatiyirisarux jasakiw k’achacht’araksna, khititix carService.getCar() ukan jikxatktan ukax, kuna kasta short-circuit ukanakatix munktan ukanakampi.


Aka uñacht’awina, mä TimeLiter , mä BulkHead ukat mä CircuitBreaker qillqt’apxta. Tukuyañatakix, mä TimeoutException ukax utjki ukhax fallback función ukax ch’amanchatäñapatakiw qhanañcht’apxtanxa. Kuntix wali uñjañax wakiski ukax kunjams akax taqpach wakicht’ata. Jiwasax Resilience4J ukax Spring ukanx wakicht’tanwa kunjamatix yaqha módulo configurable ukhama. Jiwasax application.yml apnaqapxta :

 resilience4j.circuitbreaker: configs: default: registerHealthIndicator: true slidingWindowSize: 10 minimumNumberOfCalls: 5 permittedNumberOfCallsInHalfOpenState: 3 automaticTransitionFromOpenToHalfOpenEnabled: true waitDurationInOpenState: 5s failureRateThreshold: 50 eventConsumerBufferSize: 10 recordExceptions: - org.springframework.web.client.HttpServerErrorException - java.util.concurrent.TimeoutException - java.io.IOException ignoreExceptions: # - io.github.robwin.exception.BusinessException shared: slidingWindowSize: 100 permittedNumberOfCallsInHalfOpenState: 30 waitDurationInOpenState: 1s failureRateThreshold: 50 eventConsumerBufferSize: 10 ignoreExceptions: # - io.github.robwin.exception.BusinessException instances: cars: baseConfig: default roads: registerHealthIndicator: true slidingWindowSize: 10 minimumNumberOfCalls: 10 permittedNumberOfCallsInHalfOpenState: 3 waitDurationInOpenState: 5s failureRateThreshold: 50 eventConsumerBufferSize: 10 # recordFailurePredicate: io.github.robwin.exception.RecordFailurePredicate resilience4j.retry: configs: default: maxAttempts: 3 waitDuration: 100 retryExceptions: - org.springframework.web.client.HttpServerErrorException - java.util.concurrent.TimeoutException - java.io.IOException ignoreExceptions: # - io.github.robwin.exception.BusinessException instances: cars: baseConfig: default roads: baseConfig: default resilience4j.bulkhead: configs: default: maxConcurrentCalls: 100 instances: cars: maxConcurrentCalls: 10 roads: maxWaitDuration: 10ms maxConcurrentCalls: 20 resilience4j.thread-pool-bulkhead: configs: default: maxThreadPoolSize: 4 coreThreadPoolSize: 2 queueCapacity: 2 instances: cars: baseConfig: default roads: maxThreadPoolSize: 1 coreThreadPoolSize: 1 queueCapacity: 1 resilience4j.ratelimiter: configs: default: registerHealthIndicator: false limitForPeriod: 10 limitRefreshPeriod: 1s timeoutDuration: 0 eventConsumerBufferSize: 100 instances: cars: baseConfig: default roads: limitForPeriod: 6 limitRefreshPeriod: 500ms timeoutDuration: 3s resilience4j.timelimiter: configs: default: cancelRunningFuture: false timeoutDuration: 2s instances: cars: baseConfig: default roads: baseConfig: default

Aka qillqataxa mä uñacht’awi qillqatawa jupanakana repo ukanakata apsuta ukatxa ukarjamawa nayan uñacht’awijaru mayjt’ayata. Kunjamtix nayraqat uñjawayktanxa, instancias de los diferentes tipos de limiters/short-circuit , mä sutimpiw uñt’ayasi. Sutixa wali wakiskiriwa kunaymana registros ukatxa kunaymana limitadores ukanakampi. Jiwasan uñacht’äwisatakix, ukat kunjamtï nayraqat arsuwayktanxa, pacha limitador ukarux munapxtanwa. Jiwasax uñjaraksnawa, ukax 2s ukhakiw utji. Kunjams servicio ukax phuqhasiwayi uk uñakipt’añäni ukhax mä tiempo de espera ukar obligañaw uñjasi:

 @Component open class CarService { open fun getCar(): Mono<Car> { return Mono.just(Car("Fiat")).delayElement(Duration.ofSeconds(10)); } }

Aplicación qalltañäni, ukatx navegador ukanx, aka chiqar sarañäni: http://localhost:8080/cars/test/2 . Fiat ukat sipansa, Rolls Royce sat auto apsuñäni. Ukhamatwa pacha tukuyañ qhanañchapxta. Ukhamaraki, mä CircuitBreaker jasakiw lurasispa.

3. Caso ukaxa

Jichhakamax kimsa wakiskir thakhinak uñjtanwa CircuitBreakers ukat ukar uñtasit limitadores ukanakar phuqhañataki. Ukhamarus, mä uñakipäwiw utjani, nayan munat thakhix interruptores ukanakar phuqhañataki, mä aplicación luratax tuqi, ukax mä jach’a anatawiwa kawkhantix cuadrados ukar ch’iqt’añakiw París markat Berlín markar puriñatakiki. Anatañax kunjams phuqhañax uk amuyañatakiw lurasiwayi. Kawkhans ukax phuqhasispa ukxat janiw sinti arsuwaykiti. Mä caso ukhamakiwa, nayax jumanakamp yatiñanak uñt’ayañatakiw lurawayta.


Uka yatiña-kunawsatix nayax jaytawaykta jumanakar qhipat amtañamataki. Chiqpachanx mä qawqha autonak lurañ munapxta ukat Berlín markar mä thakhi utt’ayañ munapxta. Kunayman chiqanakanx aka thakhinx markanakaruw puriñäni kawkhantix aleatoriamente, jan walt’awinak uñstayañäni. Jiwasan circuit breakers qawqha pachas suyt’añax wakisispa uk amtapxani, janïr nayrar sartañax jaysatäkipanxa. Mayni autonakajj janiw kuna jan waltʼäwinïpkiti, ukat cheqa thak ajlliñakiw wakisi.


Jiwasax mä horario uñakipañaw jaysatätanxa kawkhantix qillqantatäki kunapachatix mä jan walt’awix mä markan mä minuto markan utjani. Minuto markax 0 indexado ukanx wali askiwa. Ukax sañ muniw 2 ukax sañ muniw every 2, 12, 22, 32, 42, 52 minutos chimpunakax reloj ukanx walikïskaniwa aka jan walt’äw uñstayañataki. Jan walt’awinakax 2 kastawa: ERROR ukat TIMEOUT . Mä pantjasiw pantjasiwix 20 segundos ukjaw qhipharxani.


Mä tiempo de espera ukax 50 segundos ukjaw qhipharxani. Sapa markan mayjt’awipatakix taqiniw 10 segundos suyt’apxañapa. Ukampirus janïr suyt’kasax autox niyaw aka markar mantañ chiqankxi kunawsatix ukax fallback métodos ukan luratäki ukhaxa. Ukhamächi ukhaxa, jutïr markax aleatoriamente ajllitäxiwa.

Anatañ Panka

4. Phuqaña

Nayraqat uñjtanwa, kunjams resilience4j registro ukar wakicht’añax application.yml apnaqasa. Ukham lurasax mä qawqha uñacht’äwinakat uñakipt’añäni, kunjams jiwasan lurawinakas k’achacht’añasa:

 @TimeLimiter(name = CarService.CARS, fallbackMethod = "reportTimeout") @CircuitBreaker(name = CarService.CARS, fallbackMethod = "reportError") @Bulkhead(name = CarService.CARS) open fun moveToCity(id: Long): Mono<RoadRace> { val myCar = roadRace.getMyCar() if (!myCar.isWaiting()) { val destination = myCar.location.forward.find { it.id == id } val blockage = destination?.blockageTimeTable?.find { it.minute.toString().last() == LocalDateTime.now().minute.toString().last() } blockage?.let { roadBlockTime -> when (roadBlockTime.blockageType) { BlockageType.TIMEOUT -> return Mono.just(roadRace).delayElement(Duration.ofSeconds(10)) BlockageType.ERROR -> return Mono.create { it.error(BlockageException()) } BlockageType.UNKNOWN -> return listOf(Mono.create { it.error(BlockageException()) }, Mono.just(roadRace).delayElement(Duration.ofSeconds(10))).random() else -> print("Nothing to do here!") } } destination?.let { myCar.delay(10) myCar.location = it myCar.formerLocations.add(myCar.location) } } return Mono.just(roadRace) } private fun reportError(exception: Exception): Mono<RoadRace> { logger.info("---- **** error reported") roadRace.getMyCar().delay(20L) roadRace.getMyCar().randomFw() roadRace.errorReports.add("Error reported! at ${LocalDateTime.now()}") return Mono.create { it.error(BlockageException()) } } private fun reportTimeout(exception: TimeoutException): Mono<RoadRace> { logger.info("---- **** timeout reported!") roadRace.getMyCar().delay(50L) roadRace.getMyCar().randomFw() roadRace.errorReports.add("Timeout reported! at ${LocalDateTime.now()}") return Mono.just(roadRace) }


Kunjamtï uñjktanxa, servicio original jawsatanakax anotaciones apnaqasaw chiqak k’achacht’ata! Ukax lurasispawa kunatix módulo AOP ukax paquete ukan utjatapatakiwa:

 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>

AOP , jan ukax Aspect Oriented Programming ukax yaqha paradigma de programación ukawa, ukax OOP ukarjam luratawa. Ukax OOP ukar mä complemento ukhamaw uñjasi, ukatx chiqpachapuniw qawqha anotaciones ukanakas irnaqapxi. Ukhamatwa yaqha lurawinakax nayrïr lurawimp muyuntat, nayraqat jan ukax qhipat chiqapar khuchhuqañanakan ch’amanchañapataki. Kunjamtix uñacht’äwin uñjktanxa, jiwasax pacha tukuyañ jan ukax pantjasiwinak lurasktanxa. BlockageException , ukax fallback uka thakhi manqhanx luratarakiwa. Ukajj janiw mä jan waltʼäwir uñtasitäkiti. Jan ukax jaysawix janiw ukhamäkiti.


Ukampirus, lurawix WebSockets, ukat ukatw, aka pantjasiwix janiw apnaqawin uñjatäkaniti. Jichhakamax akax anatt’awiwa. Nayax ukax kunjams anotaciones apnaqañax jakäwisax juk’amp jasak luraspa uk uñacht’ayañ amtampiw phuqhawayta, kunawsatix mä aplicación resiliente ukar phuqhasktan ukhaxa. Janiw CircuitBreakers ukakix phuqhatäkiti, jan ukasti yaqha tecnologías ukanakaw utjaraki, WebSockets , Spring WebFlux , Docker , NGINX , typescript , ukat walja yaqhanaka. Taqi ukax luratawa kunjams CircuitBreakers ukax mä aplicación ukan anataspa uk uñjañataki. Aka aplicación ukamp anatt’añ munsta ukhax proyecton saphipar sarañamawa ukat t’ijt’añamawa:

 make docker-clean-build-start


Ukatxa aka kamachi phuqhaña:

 curl -X POST http://localhost:8080/api/fptb/blockage -H "Content-Type: application/json" --data '{"id":1,"name":"Paris","forward":[{"id":2,"name":"Soissons","forward":[{"id":5,"name":"Aken","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":6,"name":"Heerlen","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":7,"name":"Düren","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":3,"name":"Compiègne","forward":[{"id":5,"name":"Aken","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":6,"name":"Heerlen","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":7,"name":"Düren","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":4,"name":"Reims","forward":[{"id":5,"name":"Aken","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":6,"name":"Heerlen","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]},{"id":7,"name":"Düren","forward":[{"id":8,"name":"Berlin","forward":[],"blockageTimeTable":[]}],"blockageTimeTable":[]}],"blockageTimeTable":[]}],"blockageTimeTable":[]}'


Aka mayiwix payload ukax módulo from-paris-to-berlin-city-generator ukampiw lurasi. Aka módulo ukar uñakipt’asax uñjañamawa, amuyañax wali ch’amawa ukat juma pachpaw anatañatakix mapa lurasma! Tukuyañatakix http://localhost:9000 ukar sarañamawa ukatx aplicación ukax apnaqañapawa! Jichhaxa, anataña anatañatakixa chiqa cuadrado ukanakaru ch’iqt’añakiw wakisi. Ukampis janiw wila masinakarux ch’iqt’añamäkiti, atipt’añ munsta ukhaxa. Ukampirus circuito-interruptor ukan lurawipan uñjañ munsta ukhax, ukatx aplicación ukan registronakap apnaqañamawa:

 docker logs from_paris_to_berlin_web -f

Ukat qhanpachax wila cuadradonakaruw ch’iqt’añama, ukhamat mä pantjasiw utjañapataki.

5. Kunjams Kystrix ukat Resilience4J ukax mayj mayja

Kystrix ukax wali askiwa kawkhantix aplicación ukax jisk’akiwa, ukatx DSL apnaqañax chiqpachans jisk’akiwa. Ukax mä jan walt’awikiwa, kunatix janiw mä jasak thakhi uñacht’aykiti k’achacht’añ thakhinak mä interruptor ukamp jan walt’ayasiñataki. Resilience4J ukax mä jach’a amtawiw empresan irnaqañatakix interruptores ukanakamp uñt’ayasi. Chiqans anotación ukarjam programación ukaw utji, taqi beneficios van AOP ukampiw apnaqasi, ukatx módulos ukanakax jaljatawa. Mä arunxa, estratégicamente apnaqasirakispawa puntos críticos ukanakatakix aplicación ukanxa. Ukhamaraki, mä phuqhat marco ukham apnaqasirakispawa, mä aplicación ukan walja askinak uñakipañataki.

6. Tukuyañataki

Kawkïr markas ajlliñäni, amtäwix sapa kutiw mä aplicación resiliente ukaniña. Aka qillqatanx mä qawqha uñacht’awinak uñacht’ayawayta, kunjams naya pachpax interruptores ukanakat yatxatañ yatiqawayta ukat jikxatatanakajax wali jach’a nivelanwa. Ukax sañ muniw aka qillqatax chiqpachans jaqinakatakiw qillqt’ata, jupanakax yatiñ munapxi kunas interruptores ukat kuns Limiters ukanakax lurapxaspa.


Posibilidades ukax chiqpachanx janiw tukuskiti kunawsatix amuyt'ktan jiwasan aplicaciones ukanakax mecanismos de resiliencia ukanakamp circuit breakers ukham askinchañataki . Aka patrón ukax chiqpachans mä aplicación ukan suma askichañapatakiw jayti, ukhamat kunatix utjkistu ukanak juk’amp sum apnaqañataki. Jilpachax cloud ukanx wali wakiskiriwa, jiwasan qullqinak sum apnaqañax, ukatx qawqha yänaks chiqpachanx jaljañax wakisi.


CircuitBreakers ukar wakicht’añax janiw mä jisk’a lurawikiti kunjamatix Limiters ukanakatakix ukhama, ukat chiqpachans taqi configuración ukan lurawinakap amuyañaw wakisi, ukhamat niveles óptimos de rendimiento ukat resiliencia ukar puriñatakiki. Ukatwa aka qallta qillqatanx interruptores ukanakat jan juk’amp yatxatañ munkti.


Circuit-breakers walja kunaymana lurawinakaru apnaqatarakiwa. Jilpacha yatiyawinak ukhamarak streaming kasta aplicacionanakax ukax munasini. Aplicaciones ukatakix jach’a volúmenes de datos ukanak apnaqapxi ukax wali jach’a utjañapawa, jiwasax mä forma de interruptor de circuito ukarux phuqharaksnawa ukat phuqhañasarakiwa. Jach’a aljirinakax internet tuqinx sapa uruw jach’a yatiyawinak apnaqañax wakisi ukatx nayra pachanx Hystrix wali apnaqatawa. Jichhax Resilience4J uka thakhinjam sarasktan ukhamaw uñstaski ukax akat sipans juk’ampiruw uñt’ayi.

6. Uñakipt’atanaka

Pay suma!

¡Aka qillqat lurañax nayatakix wali askïspawa sasaw suyt’askta! Mä revisión, comentarios, jan ukax kuna retroalimentación ukanakatix sociales ukanakat churañ munkta ukanak aka links ukan jaytañamawa. Aka qillqat juk’amp sum lurañatakix yanapt’añ munapxsta ukhax walpun yuspärta. Nayax taqi uka aplicación ukan código fuente ukar GitHub ukan uñt’ayawayta. ¡Liytʼapjjatamat yuspärapjjsmawa!

L O A D I N G
. . . comments & more!

About Author

João Esperancinha HackerNoon profile picture
João Esperancinha@jesperancinha
Software Engineer for 10+ Years, OCP11, Spring Professional 2020 and a Kong Champion

HANG TAGS ukax mä juk’a pachanakanwa

AKA ARTÍCULO UKHAMARAKI UKHAMARAKI...