熔断器Hystrix
ribbon+Hystrix
- 使用笔记0x2的eurekaribbon工程,在pom中增加hystrix的起步依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 在application启动类中添加@ EnableHystrix,开启Hystrix
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class EurekaribbonApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaribbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
- 改造RibbonService,加上@HystrixCommand,创建熔断器
@Service
public class RibbonService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "errorService")
public String niceService(String name) {
return restTemplate.getForObject("http://EUREKACLIENT/nice?name=" + name, String.class);
}
public String errorService(String name) {
return "sorry," + name;
}
}
注解HystrixCommand指定fallbackMethod熔断方法,熔断方法返回抱歉提示的字符串
feign+Hystrix
@FeignClient(value = "eurekaclient", fallback = InvokeServiceHystric.class)
public interface InvokeService {
@RequestMapping(value = "/nice", method = RequestMethod.GET)
String sayService(@RequestParam(value = "name") String name);
}
- InvokeServiceHystric需要实现InvokeService,并注入到ioc中
@Component
public class InvokeServiceHystric implements InvokeService {
@Override
public String sayService(String name) {
return "sorry," + name;
}
}
命令
- 查看端口进程命令 lsof -i:-P
P为端口号例如:lsof -i:4200
- 关闭进程命令 kill -9 [pid]
熔断器Hystrix
ribbon+Hystrix
注解HystrixCommand指定fallbackMethod熔断方法,熔断方法返回抱歉提示的字符串
sorry,hdusdhu
feign+Hystrix
使用笔记0x3的eurekafeign工程,在配置文件中开启熔断器
feign.hystrix.enabled=true对InvokeService进行改造在@ FeignClient注解中加入fallback的指定类
sorry,hugeterry
命令
P为端口号例如:lsof -i:4200