Spring Cloud Hystrix:服务容错与熔断
Spring Cloud Hystrix 是 Netflix 的 Hystrix 的 Spring Cloud 封装,提供了服务的容错和熔断机制。
以下是一个使用 Hystrix 的简单示例:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 在你的应用主类或者配置类上添加
@EnableCircuitBreaker
注解启用 Hystrix:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableCircuitBreaker
@EnableDiscoveryClient
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
- 使用 HystrixCommand 或 HystrixObservableCommand 创建服务调用的容错逻辑:
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
public class ServiceCallCommand extends HystrixCommand<String> {
private final RestTemplate restTemplate;
private final String serviceUrl;
protected ServiceCallCommand(Setter setter, RestTemplate restTemplate, String serviceUrl) {
super(setter);
this.restTemplate = restTemplate;
this.serviceUrl = serviceUrl;
}
@Override
protected String run() throws Exception {
return restTemplate.getForObject(serviceUrl, String.class);
}
@Override
protected String getFallback() {
return "Fallback message";
}
public static class Factory {
private final RestTemplate restTemplate;
private final String serviceUrl;
@Autowired
public Factory(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
this.serviceUrl = "http://your-service-url";
}
public ServiceCallCommand create() {
return new ServiceCallCommand(Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("ServiceCallGroup")),
restTemplate, serviceUrl);
}
}
}
- 在你的服务中调用 HystrixCommand:
public String
评论已关闭