-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
Description
熔断器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熔断方法,熔断方法返回抱歉提示的字符串
- 关闭端口8662,8664的进程,请求http://localhost:8661/b?name=hdusdhu ,此时熔断器发挥作用,会看到
sorry,hdusdhu
feign+Hystrix
-
使用笔记0x3的eurekafeign工程,在配置文件中开启熔断器
feign.hystrix.enabled=truefeign本身含有熔断器,D版本后默认没有打开
-
对InvokeService进行改造在@ FeignClient注解中加入fallback的指定类
@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;
}
}- 启动eurekafeign服务,打开http://localhost:8665/feign?name=hugeterry ,会正确显示8662,8664的端口返回报文,将8662,8664进程关闭,此时熔断器响应,看到返回如下报文:
sorry,hugeterry
命令
- 查看端口进程命令 lsof -i:-P
P为端口号例如:lsof -i:4200 - 关闭进程命令 kill -9 [pid]
Reactions are currently unavailable