一、基于 Ribbon + Hystrix
在入口类 中 加上@EnableHystrix //表示加载熔断器功能
package com.springcloud.ribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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;
/**
* 本例中使用Eureka服务中心所以用@EnableEurekaClient
* 如果注册中心是zookeeper或其它,建议使用@EnableDiscoveryClient
**/
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix //表示加载熔断器功能
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
//声明RestTemplate并添加@Bean和@LoadBalanced, @LoadBalance表示支持Ribbon的负载均衡。
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
修改service层 增加
@HystrixCommand(fallbackMethod = "errCallBack") //被调用服务出现异常时,执行回调函数
package com.springcloud.ribbon.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;
/**
* Created by joe强 on 2018/9/27 20:01
*/
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "errCallBack") //被调用服务出现异常时,执行回调函数
public String doSomething(String parm){
String result;
result=restTemplate.getForObject("http://server1/ribbon?parm="+parm,String.class);//调用server1客户端 de ribbon接口
System.out.println(result);
return result;
}
/**
* 回调函数 返回值类型和原函数相同
* 回调函数参数类型和原函数相同
* @param parm
* @return
*/
public String errCallBack(String parm){
return "Sorry,"+parm+",server1 not responde";
}
}
启动Ribbon服务 和 server1 ,调用接口
此时 接口调用没有问题 ,现在 关闭server1 服务,再次调用接口:
调用发生异常时,熔断机制生效了!
二、Feign +Hystrix
第一步:首先开启Feign对Hystrix的支持,在properties文件中添加以下配置:
feign.hystrix.enabled=true.
第二部 修改 Server1Service 接口
新增Server1Service实现类:
package com.springcloud.feign.service;
import org.springframework.stereotype.Component;
/**
* Created by joe强 on 2018/9/28 15:34
*/
@Component
public class Server1ServiceImpl implements Server1Service {
@Override
public String callribbonByFegin(String parm) { //参数不需要@RequestParm
return "Sorry," + parm + "server1 not responde";
}
}
启动 Feign服务,此时 开启server1 客户端,调用接口:
调用没有任何问题,此时关闭server1 客户端 再次调用接口:
发生异常,熔断机制生效!