Ribbon+Hystrix代码冗余严重,使用Feign+Hystrix可以抽象服务调用以及统一服务失效降级。
在上一篇注册中心和服务提供者配置的基础上
创建子工程——》Eureka Client + Feign + Hytrix
配置文件
spring:
application:
name: ribbon-consumer
server:
port: 8090
eureka:
client:
service-url:
defaultZone: http://localhost:8888/eureka/
register-with-eureka: false
fetch-registry: true
provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
#开启hystrix断路器
feign:
hystrix:
enabled: true
服务启动类 添加注解
@EnableHystrix @EnableFeignClients(basePackages = {"com.wxl"}) @EnableDiscoveryClient @SpringBootApplication @ComponentScan(basePackages = {"com.wxl"})
消费者接口类
@RestController
public class RibbonController {
@Autowired
private ConsumerFeignClient consumerFeignClient;
@GetMapping("/consumer")
public String getMsg() {
return consumerFeignClient.getMsg();
}
}
调用服务的Feign客户端
// 名称和服务名一致,服务失效的话则调用本地方法 降级处理
@FeignClient(value = "provider",fallback = ConsumerFeignFallBack.class)
public interface ConsumerFeignClient {
// 路由参数和服务中的方法一致
@RequestMapping(value = "/learn", method = RequestMethod.GET)
String getMsg();
}
服务调用失败,会调用本地服务,来统一提示
@Component
public class ConsumerFeignFallBack implements ConsumerFeignClient {
@Override
public String getMsg() {
return "服务失效,降级处理";
}
}
关闭服务 ,测试降级处理