说明:这里只说明熔断使用,不对作用进行解释介绍
准备:需要A服务 B服务都注册到注册中心,A服务需要调用B服务,那么熔断就是在B服务中。我这边A服务调用B服务是用的openfeign。
A服务内容【一些注册中心配置就不整了】:
pom文件:我这里面跟熔断相关的配置没有
yml文件:我这里面跟熔断相关的配置没有
控制层:ATestController
@Autowired private ATestService atestService; @GetMapping("forHystrix") public String forHystrix(@RequestParam("a") int a){ return atestService.forHystrix(a); }
接口层:
@FeignClient(name = "B服务名称") public interface ATestService { @GetMapping("forHystrix") String forHystrix(@RequestParam("a") int a); }
接口实现层【这个是做降级的,要不要都行】:
@Service public class ATestServiceImpl implements ATestService { public String forHystrix(int a){ return "我是降级-forHystrix"; } }
B服务内容:
pom文件:
<!-- hystrix 熔断 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
yml文件:
hystrix: metrics: enabled: true
启动类:在启动类上加上 @EnableHystrix//开启熔断
控制层:BTestController
@Autowired private BTestService btestService; @GetMapping("forHystrix") public String forHystrix(@RequestParam("a") int a){ a = btestService.forHystrix(a); return "hello forHystrix: a = "+ a; }
接口层:
public interface BTestService { int forHystrix(int a); }
接口实现类:
@Service public class BTestServiceImpl implements BTestService { @HystrixCommand(fallbackMethod = "forHystrixError",commandProperties = { @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启路由 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//请求失败率 })//上面的配置意思是,开启路由,每请求10次该接口,有6次请求失败,那么Hystrix会开启服务熔断 public int forHystrix(int a) { System.out.println(a); if(a == 1){ int b = 1/0; } return a; } public int forHystrixError(int a){ return -1; } }
随便记录一下。。。。。。。。。。。