服务中心,注册服务,调用服务完成以后。多个服务关联性调用,有时候,出现服务链式调用,如果上层奔溃,大批量的请求整个下层全部奔溃。对于这种情况,springclud给我们提供了,熔断器-Hystrix
1.application.properties配置文件增加开启熔断配置
spring.application.name=spring-cloud-consumer server.port=9001 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/ #######熔断器开启########### feign.hystrix.enabled=true
2.新增接口的实现类,作用,服务失败,熔断器调用
package com.example.servicefeign.impleServer; import com.example.servicefeign.interfaceServer.HelloRemote; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestParam; @Component//将实现通过bean注入 public class HelloRemoteHystrix implements HelloRemote { @Override public String hello(@RequestParam(value = "name") String name){ return "熔断器返回结果:" + name; } }
@Component 通过注解,将其作为bean对象
3.FeignClient注解中,增加失败返回类的引用
package com.example.servicefeign.interfaceServer; import com.example.servicefeign.impleServer.HelloRemoteHystrix; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name= "spring-cloud-producer",fallback = HelloRemoteHystrix.class) //name:远程服务名,及spring.application.name配置的名称 //服务熔断的时候返回fallback类中的内容 public interface HelloRemote { @RequestMapping(value = "/hello") String hello(@RequestParam(value = "name") String name); }
FeignClient里面,增加fallback,失败回调类。
测试,将注册的服务程序,直接停止,进行访问,返回成功