Spring Cloud Circuit Breaker基础入门与服务熔断
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker.RunFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class CircuitBreakerService {
@Autowired
private CircuitBreakerFactory circuitBreakerFactory;
public String callWithCircuitBreaker(String serviceName) {
CircuitBreaker cb = circuitBreakerFactory.create(serviceName);
RunFunction<String> call = () -> "Service " + serviceName + " is up!";
return cb.run(call);
}
public Mono<String> callWithCircuitBreakerReactive(String serviceName) {
CircuitBreaker cb = circuitBreakerFactory.create(serviceName);
return cb.run(() -> Mono.just("Service " + serviceName + " is up!"), throwable -> Mono.just("Service " + serviceName + " is down!"));
}
}
这个简单的服务类展示了如何在Spring Cloud应用中使用断路器模式。callWithCircuitBreaker
方法用于同步调用,并返回一个字符串。callWithCircuitBreakerReactive
方法用于反应式调用,返回一个Mono对象。在实际应用中,你可以将这些方法应用到服务调用中,以保护你的系统不受服务故障的影响。
评论已关闭