Spring Cloud Hystrix:服务容错保护
Spring Cloud Hystrix 是 Netflix 的 Hystrix 的一个 Spring 集成,用于提供分布式系统的服务容错保护。以下是一个使用 Hystrix 的简单示例:
- 添加 Maven 依赖:
<dependencies>
<!-- Spring Cloud Hystrix 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- Spring Cloud 版本管理 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 在 Spring Boot 应用的主类或者配置类上添加
@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 包装可能失败的服务调用:
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(RestTemplate restTemplate, String serviceUrl) {
super(HystrixCommandGroupKey.Factory.asKey("ServiceCallGroup"));
this.restTemplate = restTemplate;
this.serviceUrl = serviceUrl;
}
@Override
protected String run() {
return restTemplate.getForObject(serviceUrl, String.class);
}
@Override
protected String getFallback() {
return "Fallback message - service is unavailable";
}
}
- 在服务中调用 HystrixCommand:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyS
评论已关闭