在Ribbon中添加Hystrix
在pom.xml添加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在RibApplication上方
寫(xiě)上
@EnableHystrix
開(kāi)啟熔斷器
@EnableHystrix
@SpringBootApplication
@EnableDiscoveryClient
public class RibApplication {
public static void main(String[] args) {
SpringApplication.run(RibApplication.class, args);
}
}
修改Service
@Service
public class ClientService {
@Autowired
private RestTemplate restTemplate;
//當(dāng)程序出現(xiàn)錯(cuò)誤時(shí)候熔斷并調(diào)用hiError
@HystrixCommand(fallbackMethod = "hiError")
public String sayHi(String message) {
System.out.println(message);
return restTemplate.getForObject("http://client/hi?message="+message,String.class);
}
//寫(xiě)一段返回錯(cuò)誤信息的方法
public String hiError(String message){
return String.format("Hi your message is : %s but request bad",message);
}
}
在Feign中添加Hystrix
feign:
hystrix:
enabled: true
()最后)
spring:
application:
name: feign
server:
port: 8789
feign:
hystrix:
enabled: true
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8081/eureka/
Application無(wú)變化
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
Service 下創(chuàng)建hystrix目錄
并創(chuàng)建FeignHystrix.class

image.png
實(shí)現(xiàn)FeignService
并標(biāo)注
@Component注解
@Component
public class FeignHystrix implements FeignService {
@Override
public String sayHi(String message) {
return String.format("Hi your message is err" + message);
}
}
改造FeignService
加上fallback = 熔斷回調(diào)方法
@FeignClient(value = "client",fallback = FeignHystrix.class)
public interface FeignService {
@RequestMapping(value = "hi",method = RequestMethod.GET)
String sayHi(@RequestParam(value = "message") String message);
}
添加熔斷儀表盤(pán)監(jiān)控
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
添加@EnableHystrixDashboard
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableHystrixDashboard
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
創(chuàng)建HystrixDashboardConfiguration

@Configuration
public class HystrixDashboardConfiguration {
@Bean
public ServletRegistrationBean getServlet(){
//創(chuàng)建servlet
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
//servlet注冊(cè)bean
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
//servlet創(chuàng)建時(shí)機(jī)
registrationBean.setLoadOnStartup(1);
//servlet映射路徑
registrationBean.addUrlMappings("/hystrix.stream");
//servlet名稱(chēng)
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
相當(dāng)于創(chuàng)建了一個(gè)servlet
(對(duì)應(yīng)字段對(duì)比)

image.png
啟動(dòng)feign
訪問(wèn)http://localhost:8789/hystrix

image.png