Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.
译:Netflix创建了一个名为hystrix的库,用于实现断路器模式。在微服务体系结构中,通常有多个服务调用层。关键单词:hystrix断路器 fallback RIBBON:fallbackMethod
在这边有个非常容易熟悉的小窍门。hystrix称为断路,那么我们可以把fallback理解为前面路断了,所以需要给自己留条后路。
个人理解:当注册中心的某一个服务挂了之后,我们再去进行访问,通过断路器可以设置得到一个返回信息,去进行处理
先基于ribbon去进行处理 修改前面示例的ribbon
<!--添加断路器依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在启动类上加上注解
package com.tg.rabbin_customer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient //启动一个eureka的客户端
@EnableHystrix //激活断路器
public class RabbinCustomerApplication {
public static void main(String[] args) {
SpringApplication.run( RabbinCustomerApplication.class, args );
}
//开启负载均衡功能
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
对service层进行小小的改造
package com.tg.rabbin_customer;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
//编写一个接口
@Service
public class RestHeloService {
@Autowired
private RestTemplate restTemplate;
//调用eureka注册中心的服务
//<<<< /使用注解 fallbacMethod当调用服务的时候当EUREKA-CLIENT服务不可用的时候直接执行error方法返回字符串 >>>>
@HystrixCommand(fallbackMethod = "error")
public String toSay() {
return restTemplate.getForObject( "http://EUREKA-CLIENT/hi", String.class );
}
//当服务器执行报错执行的回调方法
private String error(){
return "hi.error";
}
}
然后启动项目采用浏览器进行访问
服务可用的情况就不演示了
服务不可用情况
Feign 使用断路器
feign在之前已经解释过了 集成了ribbon feign是自带断路器的但是默认是没有打开的 所以需要通过配置文件去进行开启
Feign自带断路器 所以不需要添加依赖!
feign:
hystrix:
enabled: true
跟ribbon类似都是在service进行修改
新建一个类去实现RestHiService 必须注入进容器 所以Component这个注解不能少!!!!
package com.tg.feign_demo;
import org.springframework.stereotype.Component;
@Component
public class SchedualServiceHiHystric implements RestHiService {
@Override
public String sayHi() {
return "errorcode 404";
}
}
package com.tg.feign_demo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
//FeignClient 直接定义该当前接口对应的注册中心 的服务名
@FeignClient(value = "EUREKA-CLIENT", fallback = SchedualServiceHiHystric.class)
public interface RestHiService {
//对应的服务中心的服务方法
@GetMapping(value = "/hi")
public String sayHi();
}