在Ribbon中添加Hystrix
在pom.xml添加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在RibApplication上方
写上
@EnableHystrix
开启熔断器
@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;
//当程序出现错误时候熔断并调用hiError
@HystrixCommand(fallbackMethod = "hiError")
public String sayHi(String message) {
System.out.println(message);
return restTemplate.getForObject("http://client/hi?message="+message,String.class);
}
//写一段返回错误信息的方法
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无变化
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
Service 下创建hystrix目录
并创建FeignHystrix.class
实现FeignService
并标注
@Component
注解
@Component
public class FeignHystrix implements FeignService {
@Override
public String sayHi(String message) {
return String.format("Hi your message is err" + message);
}
}
改造FeignService
加上fallback = 熔断回调方法
@FeignClient(value = "client",fallback = FeignHystrix.class)
public interface FeignService {
@RequestMapping(value = "hi",method = RequestMethod.GET)
String sayHi(@RequestParam(value = "message") String message);
}
添加熔断仪表盘监控
<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);
}
}
创建HystrixDashboardConfiguration
@Configuration
public class HystrixDashboardConfiguration {
@Bean
public ServletRegistrationBean getServlet(){
//创建servlet
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
//servlet注册bean
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
//servlet创建时机
registrationBean.setLoadOnStartup(1);
//servlet映射路径
registrationBean.addUrlMappings("/hystrix.stream");
//servlet名称
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
相当于创建了一个servlet
(对应字段对比)
启动feign
访问http://localhost:8789/hystrix