一、在前文基礎上咱們以MyClient和MyServer爲例java
二、MyClient引入依賴web
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
三、在程序的啓動類MyClientApplication加@EnableHystrix註解開啓Hystrixspring
package com.myclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @EnableEurekaClient //啓動EnableEureka客戶端 @EnableDiscoveryClient @SpringBootApplication @EnableHystrix public class MyClientApplication { public static void main(String[] args) { SpringApplication.run(MyClientApplication.class, args); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } }
四、改造DemoService類,在hiService方法上加上@HystrixCommand註解。該註解對該方法建立了熔斷器的功能,並指定了fallbackMethod熔斷方法,熔斷方法直接返回了一個字符串,字符串爲"hi,"+name+",sorry,error!",代碼以下:瀏覽器
package com.myclient.demo.service; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class DemoService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "hiError") public String hiService(String name) { return restTemplate.getForObject("http://MYSERVER/myserver/demo/hello/"+name,String.class); } public String hiError(String name) { return "hi,"+name+",sorry,error!"; } }
五、啓動:myclient 工程,當咱們訪問http://127.0.0.1:8081/myclient/demo/hello/jackson瀏覽器顯示:.net
六、關閉myserver的全部工程rest