目录
一、改造项目service-ribbon
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
启动类增加@EnableHystrix
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
@RestController
public class ServiceRibbonApplication {
服务类增加熔断注解
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
}
public String hiError(String name) {
return "hi,"+name+",sorry,error!";
}
}
二、测试
执行service-ribbon启动类
浏览器访问 http://localhost:8764/hi?name=forezp
hi forezp ,i am from port:8763
关闭service-hi服务
hi,forezp,sorry,error!
在service-hi的服务类里加1秒延迟
开启service-hi服务
hi,forezp,sorry,error!
熔断的时间应该在1秒之内,具体懒得测。如果去掉熔断
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Aug 20 14:55:17 CST 2019
There was an unexpected error (type=Internal Server Error, status=500).
I/O error on GET request for "http://SERVICE-HI/hi": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
http空接口错误返回。