前言:
在微服务架构中,为了高可用,单个微服务会开集群,服务与服务之间通过rpc调用时,由于网络原因或者程序问题,不可能保证每次调用都100%成功,单个服务出现问题,调用这个微服务就会出现线程阻塞,由于服务与服务之间具有依赖性,故障会传播,整个微服务系统有可能崩溃。
Hystrix:
当调用微服务在一定时间段内失败率达到某个阈值时,会默认打开Hystrix,返回其设置的默认值,此后Hystrix会进入半开路状态,每过一段时间,放开一个请求,如果请求成功则关闭熔断,否则继续半开路状态。
代码:
在上一篇博客的基础上,修改eureka 客户端,加入hystrix在客户端引入maven依赖包:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
在启动类上加上@EnableHystrix,开启Hystrix
package com.xhx.springcloud.controller; import com.netflix.discovery.converters.Auto; import com.xhx.springcloud.api.HelloFeign; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * xuhaixing * 2018/6/3 16:27 */ @RestController @EnableEurekaClient @EnableHystrix public class RibbionController { @Autowired private HelloFeign helloFeign; @RequestMapping(value = "getName") public String getName(String name){ return helloFeign.getName(name); } }
创建一个熔断的类,继承feign接口:
package com.xhx.springcloud.hystrix; import com.xhx.springcloud.api.HelloFeign; import org.springframework.stereotype.Component; /** * xuhaixing * 2018/6/6 13:36 */ @Component public class HelloFeignHystrix implements HelloFeign { @Override public String getName(String name) { return "请求第三方api错误"; } }
feign接口上,加上fallback
package com.xhx.springcloud.api; import com.xhx.springcloud.hystrix.HelloFeignHystrix; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * xuhaixing * 2018/6/5 16:51 */ @FeignClient(value = "EUREKA-SERVICE",path = "hello", fallback =HelloFeignHystrix.class) public interface HelloFeign { @RequestMapping(value = "getName") public String getName(@RequestParam("name") String name);//@RequestParam 必须加上,否则可能会接不到参数 }
配置文件中开启feign熔断:
server: port: 8085 eureka: client: service-url: defaultUrl: http://localhost:8761/eureka spring: application: name: eureka-feign feign: hystrix: enabled: true
只启动eureka与请求的客户端,不启动服务端,直接访问接口:
扫描二维码关注公众号,回复:
1657113 查看本文章
启动两个服务端:
请求: