在开始使用Spring Cloud Hystrix实现断路器以前,咱们先拿以前实现的一些内容做为基础,其中包括:java
eureka-server
工程:服务注册中心,端口:1001eureka-client
工程:服务提供者,两个实例启动端口分别为2001下面咱们能够复制一下以前实现的一个服务消费者:eureka-consumer-ribbon
,命名为eureka-consumer-ribbon-hystrix
。下面咱们开始对其进行改在:web
Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码请加企鹅求求:一零三八七七四六二六
spring
第一步:pom.xml
的dependencies节点中引入spring-cloud-starter-hystrix
依赖:bash
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
复制代码 |
第二步:在应用主类中使用@EnableCircuitBreaker
或@EnableHystrix
注解开启Hystrix的使用:app
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
复制代码 |
注意:这里咱们还能够使用Spring Cloud应用中的@SpringCloudApplication
注解来修饰应用主类,该注解的具体定义以下所示。咱们能够看到该注解中包含了上咱们所引用的三个注解,这也意味着一个Spring Cloud标准应用应包含服务发现以及断路器。分布式
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {
}
复制代码 |
第三步:改造服务消费方式,新增ConsumerService
类,而后将在Controller
中的逻辑迁移过去。最后,在为具体执行逻辑的函数上增长@HystrixCommand
注解来指定服务降级方法,好比:函数
@RestController
public class DcController {
@Autowired
ConsumerService consumerService;
@GetMapping("/consumer")
public String dc() {
return consumerService.consumer();
}
class ConsumerService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fallback")
public String consumer() {
return restTemplate.getForObject("http://eureka-client/dc", String.class);
}
public String fallback() {
return "fallback";
}
}
}
复制代码 |
下面咱们来验证一下上面Hystrix带来的一些基础功能。咱们先把涉及的服务都启动起来,而后访问localhost:2101/consumer
,此时能够获取正常的返回,好比:Services: [eureka-consumer-ribbon-hystrix, eureka-client]
。微服务
为了触发服务降级逻辑,咱们能够将服务提供者eureka-client
的逻辑加一些延迟,好比:ui
@GetMapping("/dc")
public String dc() throws InterruptedException {
Thread.sleep(5000L);
String services = "Services: " + discoveryClient.getServices();
System.out.println(services);
return services;
}
复制代码 |
重启eureka-client
以后,再尝试访问localhost:2101/consumer
,此时咱们将得到的返回结果为:fallback
。咱们从eureka-client
的控制台中,能够看到服务提供方输出了本来要返回的结果,可是因为返回前延迟了5秒,而服务消费方触发了服务请求超时异常,服务消费者就经过HystrixCommand注解中指定的降级逻辑进行执行,所以该请求的结果返回了fallback
。这样的机制,对自身服务起到了基础的保护,同时还为异常状况提供了自动的服务降级切换机制。java B2B2C 源码 多级分销Springcloud多租户电子商城系统.spa
Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码请加企鹅求求:一零三八七七四六二六