Hystrix与OpenFeign集成(二)

1.服务熔断的实现

0.服务熔断的实现思路

  • 引入hystrix依赖,并开启熔断器(断路器)
  • 模拟降级方法
  • 进行调用测试

1.项目中引入hystrix 依赖(openFeign依赖中已经依赖了hystrix依赖,但是需要在配置文件中开启hystrix依赖)

<!-- 引入hystrix-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        <version>2.2.6.RELEASE</version>
    </dependency>

2.启动类上开启断路器

	@SpringBootApplication
	@EnableDiscoveryClient  //开启consul注册中心
	@EnableFeignClients  //开启openfeign
	@EnableCircuitBreaker  //开启hystrix服务熔断
	public class SchoolApplication {
    	public static void main(String[] args) {
        	SpringApplication.run(SchoolApplication.class, args);
    		}
	}

3.在controller类的方法中使用@HystrixCommand注解实现断路,两种使用方式
a.为每一个调用接口提供自定义备选处理
@HystrixCommand(fallbackMethod = "GetStudentFallbackMethod")

b.默认的服务FallBack处理方法

  • 如果为每一个服务方法开发一个降级,对于我们来说,可能会出现大量的代码冗余,不利于维护,这个时候就需要加入默认服务降级处理方法。注意:在默认方法和返回方法中会优先使用返回方法的内容
    @HystrixCommand(fallbackMethod = "GetStudentFallbackMethod",defaultFallback = "默认处理方法名")
@RequestMapping("/findStudent/{id}")
@HystrixCommand(fallbackMethod = "GetStudentFallbackMethod")
public Student GetStudent(@PathVariable("id") Integer id){
    if (id<=0){
        throw new RuntimeException("id有误!!!");
    }
    Student student = studentClient.getStudentById(id);

    return student;
}

public Student GetStudentFallbackMethod(Integer id){
    Student student = new Student();
    return student;
}

2.服务降级的实现

服务降级:站在系统整体符合角度 实现:关闭系统中某些边缘服务 保证系统核心服务运行 Emps 核心服务 Depts 边缘服务

1.客户端openfeign + hystrix

  • 引入hystrix依赖
  • 配置文件开启feign支持hystrix
  • 在feign客户端调用加入hystrix
  • 开发降级处理方法

2.开启openfeign支持服务降级【默认是没有开的,需要添加配置打开】 ,
开启openfeign支持降级

feign.hystrix.enabled=true

3.在openfeign客户端中加入Hystrix //fallback:这个属性用来指定当前调用服务不可用时,默认的备选处理

 @FeignClient(value = "STUDENT", fallback =StudentClientFallback.class)
 public interface StudentClient {...}

4.开发fallback处理类,需要实现openfeign客户端接口

@Component //注意一定要把处理类放入容器中
public class StudentClientFallback implements StudentClient {

    @Override
    public String test() {
        return "我是学校端,服务器正忙,稍后再试...";
    }

    @Override
    public Student getStudentById(Integer id) {
        return null;
    } }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值