Skip to content

Instantly share code, notes, and snippets.

View deepakmehra10's full-sized avatar
🎯
Focusing

Deepak Mehra deepakmehra10

🎯
Focusing
View GitHub Profile
private Mono<ResponseEntity> getUserFallback() {
// You can fetch the value from cache here when the service is down, if the
// fallback method also cause any exception the circuit breaker will go in
// open state accordingly after multiple failed requests(Please check
// configurations for that).
return Mono.just(ResponseEntity.ok(User.builder().id("1").name("Deepak").build()));
}
// With Fallback
@GetMapping("/fallback/users")
@CircuitBreaker(name = USER_SERVICE, fallbackMethod = "getUserFallback")
public Mono<ResponseEntity> getUserWithFallback() {
// This will cause the exception and control will be transferred to fallback method.
return Mono.error(new TimeoutException("Timeout exception occurred."));
}
// Failure
@GetMapping("failure/users")
@CircuitBreaker(name = USER_SERVICE)
public Mono<ResponseEntity> getUserWithFailure() {
// This will cause the circuit breaker to go in an open state.
return Mono.error(new TimeoutException("Timeout exception occurred."));
}
// Success
@GetMapping("success/users")
@CircuitBreaker(name = USER_SERVICE)
public Mono<ResponseEntity> getUser(@PathVariable String id) throws Exception {
return Mono.just(ResponseEntity.ok(User.builder().id("1").name("Deepak").build()));
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot2</artifactId>
<version>1.5.0</version>
</dependency>
CompletableFuture name = CompletableFuture.completedFuture("Deepak");
CompletionStage name With CompletionStage = CompletableFuture.completedStage("Deepak");
CompletableFuture failedFuture = failedFuture(new TimeoutException());
System.out.println(failedFuture.join());
public class CompleteOnTimeoutDemo {
public static void main(String[] args) {
CompletableFuture orTimeout = CompletableFuture.supplyAsync(() -> {
try {
return getUsers();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
})
public class OrTimeoutDemo {
public static void main(String[] args) {
CompletableFuture orTimeout = CompletableFuture.supplyAsync(() -> {
try {
return getUsers();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return null;
}
})
CompletableFuture completableFuture = new CompletableFuture();
CompletableFuture nameFuture = completableFuture.completeAsync(() -> "Deepak");
// Should be avoided, only for demonstration purpose
System.out.println(nameFuture.join());