springcloud hystrix熔断器
作用:在分布式系统中,服务与服务之间的依赖错综复杂, 一种不可避免的情况就是某些服务会 出现故障,导致依赖于它们的其他服务出现远程调度的线程阻塞。 Hystrix 是 Netflix 公司开 源的一个项目,它提供了熔断器功能,能够阻止分布式系统中出现联动故障。 Hystrix 是通过 隔离服务的访问点阻止联动故障的,并提供了故障的解决方案,从而提高了整个分布式系统 的弹性。
1.pom部分
父pom dependencyManagement
<dependencyManagement>
<dependencies>
<dependency>
<groupId>
org.springframework.cloud
</groupId>
<artifactId>
spring-cloud-dependencies
</artifactId>
<version>
Greenwich.RELEASE
</version>
<type>
pom
</type>
<scope>
import
</scope>
</dependency>
</dependencies>
</dependencyManagement>
消费者(客户端)pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
application.properties 文件
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 为熔断器超时时间
server.port=8090
spring.application.name=cloud3
#注册服务的地址
eureka.client.service-url.defaultZone=http://localhost:8080/eureka/
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=60000
代码部分
@EnableHystrix激活熔断器
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class SpringCloud3Application {
public static void main(String[] args) {
SpringApplication.run(SpringCloud3Application.class,args);
}
}
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
主要部分为 @HystrixCommand 注解
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod ="error")
@GetMapping("a")
public ResponseEntity test(){
String result = restTemplate.getForEntity("http://cloud1/test/a",String.class).getBody();
return ResponseEntity.ok(result);
}
public ResponseEntity error(){
return ResponseEntity.ok("error");
}
}
服务提供者出现异常或熔断器超时,请求接口返回error