Spring Cloud使用Hystrix
在Spring Cloud中使用Hystrix,你需要做以下几步:
- 引入Spring Cloud Hystrix依赖。
- 开启Hystrix支持。
- 使用
@HystrixCommand
注解指定回调方法。
以下是一个简单的示例:
pom.xml中添加依赖(使用Maven):
<dependencies>
<!-- Spring Cloud Hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
启用Hystrix支持(在Spring Boot应用上使用@EnableCircuitBreaker或@EnableHystrix注解):
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 HystrixApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixApplication.class, args);
}
}
使用HystrixCommand注解(在服务调用方法上):
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ServiceController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/service-a")
@HystrixCommand(fallbackMethod = "serviceAFallback")
public String serviceA() {
return this.restTemplate.getForObject("http://SERVICE-A/", String.class);
}
public String serviceAFallback() {
return "Service A is not available";
}
}
在上述代码中,@HystrixCommand
注解被用于serviceA()
方法,并指定了回退方法\`servic
评论已关闭