熔断器详解:Hystrix与Resilience4j
熔断器详解:Hystrix与Resilience4j
概述
熔断器是微服务架构中的重要组件。本教程介绍Hystrix和Resilience4j的使用。
1. Hystrix
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@HystrixCommand(
commandKey = "getUser",
threadPoolKey = "userPool",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
},
fallbackMethod = "getUserFallback"
)
public User getUser(Long id) {
// 可能失败的外部调用
return restTemplate.getForObject("http://user-service/api/users/" + id, User.class);
}
public User getUserFallback(Long id) {
return new User(id, "未知用户", 0);
}
}
# 配置
# application.yml
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
circuitBreaker:
requestVolumeThreshold: 10
errorThresholdPercentage: 50
sleepWindowInMilliseconds: 5000
2. Resilience4j
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.stereotype.Service;
@Service
public class ResilienceService {
@CircuitBreaker(name = "userService", fallbackMethod = "circuitBreakerFallback")
public String circuitBreakerExample() {
return callExternalService();
}
@Retry(name = "userService", fallbackMethod = "retryFallback")
public String retryExample() {
return callExternalService();
}
@Bulkhead(name = "userService", fallbackMethod = "bulkheadFallback")
public String bulkheadExample() {
return callExternalService();
}
@TimeLimiter(name = "userService")
public CompletableFuture<String> timeLimiterExample() {
return CompletableFuture.supplyAsync(this::callExternalService);
}
public String circuitBreakerFallback(Throwable t) {
return "熔断降级";
}
public String retryFallback(Throwable t) {
return "重试降级";
}
public String bulkheadFallback(Throwable t) {
return "舱壁降级";
}
private String callExternalService() {
return restTemplate.getForObject("http://external-service/api", String.class);
}
}
# 配置
# application.yml
resilience4j:
circuitbreaker:
instances:
userService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10s
permittedNumberOfCallsInHalfOpenState: 3
retry:
instances:
userService:
maxAttempts: 3
waitDuration: 500
bulkhead:
instances:
userService:
maxConcurrentCalls: 10
maxWaitDuration: 0
timelimiter:
instances:
userService:
timeoutDuration: 3s
3. 实际应用示例
熔断监控
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CircuitBreakerController {
private final CircuitBreakerRegistry registry;
public CircuitBreakerController(CircuitBreakerRegistry registry) {
this.registry = registry;
}
@GetMapping("/circuit-breaker/status")
public Map<String, String> getCircuitBreakerStatus() {
Map<String, String> status = new HashMap<>();
registry.getAllCircuitBreakers().forEach(cb -> {
status.put(cb.getName(), cb.getState().name());
});
return status;
}
}
降级策略
@Service
public class FallbackService {
@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public User getUser(Long id) {
return callUserService(id);
}
public User fallback(Long id, Throwable t) {
// 熔断降级策略
return User.builder()
.id(id)
.name("默认用户")
.status("服务降级")
.build();
}
}
4. 最佳实践
- 选择合适的熔断器:Hystrix已停止维护,推荐Resilience4j
- 合理配置阈值:根据业务需求配置熔断参数
- 实现降级策略:提供友好的降级响应
- 监控熔断状态:实时监控熔断器状态
- 测试熔断功能:确保熔断器正常工作
总结
熔断器是微服务架构中的重要组件。掌握Hystrix和Resilience4j的使用,可以构建高可用的微服务系统。