如何在 Spring Boot 中使用带有 WebFlux 的 Resilience4j 断路器

问题描述

我有服务 A 调用下游服务 B。

服务 A 代码

@RestController
@RequestMapping(value = "",produces = MediaType.APPLICATION_JSON_VALUE)
public class GreetingController {

    private final GreetingService greetingService;

    public GreetingController(GreetingService greetingService){
        this.greetingService = greetingService;
    }

    @GetMapping(value = "/greetings")
    public Mono<String> getGreetings() {
        return greetingService.callServiceB();
    }
}

@Component
@requiredArgsConstructor
public class GreetingService {
    
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("greetingService");
    Callable<Mono<String>> callable = CircuitBreaker.decorateCallable(circuitBreaker,this::clientCall);
    Future<Mono<String>> future = Executors.newSingleThreadExecutor().submit(callable);

    public Mono<String> callServiceB() {
        try {
            return future.get();
        } catch (CircuitBreakerOpenException | InterruptedException | ExecutionException ex){
            return Mono.just("Service is down!");
        }
    }


    private final String url = "/v1/holidaysgreetings";
    
    private Mono<String> clientCall(){
        WebClient client = WebClient.builder().baseUrl("http://localhost:8080").build();
        
        return client
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class);
}

当我关闭下游服务 B(在 localhost:8080 上运行)并点击 /greetings 类中的 GreetingsController 端点以查看我的断路器是否正常工作时,我得到了这个令人讨厌的错误

2021-06-28 21:27:31.431 ERROR 10285 --- [nio-8081-exec-7] o.a.c.c.C.[.[.[.[dispatcherServlet]: Servlet.service() for servlet [dispatcherServlet] in context with path [/v1/holidaysgreetings] 
threw exception [Request processing Failed; nested exception is org.springframework.web.reactive.function.client.WebClientRequestException: Connection refused: localhost/127.0.0.1:8080; 
nested exception is io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: localhost/127.0.0.1:8080] with root cause

java.net.ConnectException: Connection refused

有人知道我为什么会收到这个吗?我在这里缺少什么?我是否正确实施了断路器?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)