一、在前文基础上咱们以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