参考网址:https://blog.csdn.net/forezp/article/details/81040990
一、准备工作
启动前几篇的项目:erurekaserver,eurekaclient1
二、修改项目service-ribbon
1、修改pox.xml 添加如下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、修改ServiceRibbonApplication.java 添加@EnableHystrix注解
package wg;
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;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run( ServiceRibbonApplication.class, args );
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
3、修改HelloService.java,在方法上添加@HystrixCommand(fallbackMethod = "helloError"),并新建方法helloError。
package wg.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "helloError")
public String helloService() {
return restTemplate.getForObject("http://EUREKACLIENT/",String.class);
}
public String helloError() {
return "hi,wg,sorry,error!";
}
}
4、启动service-ribbon,访问:http://localhost:8764/hello
出现:hello world from port 8763
5、关闭eurekaclient1,访问:http://localhost:8764/hello
出现:hi,wg,sorry,error!
熔断成功。
三、修改项目service-feign
1、修改HelloService.java,添加 fallback = HelloServiceImpl.class
package wg.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value = "EUREKACLIENT",fallback = HelloServiceImpl.class)
public interface HelloService {
@RequestMapping(value = "/",method = RequestMethod.GET)
String sayHello();
}
2、新建HelloServiceImpl.java
package wg.service;
import org.springframework.stereotype.Component;
@Component
public class HelloServiceImpl implements HelloService{
@Override
public String sayHello() {
// TODO Auto-generated method stub
return "sorry,error!";
}
}
3、修改application.yml
server:
port: 8765
spring:
application:
name: service-feign
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
feign:
hystrix:
enabled: true
4、启动 service-feign,访问:http://localhost:8765/hello
出现:hello world from port 8763
5、关闭eurekaclient1,访问:http://localhost:8765/hello
出现:sorry,error!
熔断成功。