添加依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
配置文件
spring:application:name: order-service-feign #应用名称cloud:sentinel:transport:port: 8719dashboard: localhost:8080#对Feign开启对sentinel的支持feign:sentinel:enabled: true # 添加feign对sentinel的支持
如果想要做服务的容错并且要捕获日志、异常信息,那我们就可以使用fallbackFactory
熔断降级
feign的注解@FeignClient :fallbackFactory与fallback方法不能同时使用,这个两个方法其实都类似于Hystrix的功能,当网络不通时返回默认的配置数据。
ProductServiceFallback.java
/*** 服务熔断降级处理可以捕获异常/@Componentpublic class ProductServiceFallbackFactory implements FallbackFactory<ProductService>{//捕获日志,在需要捕获异常的方法进行处理Logger logger = LoggerFactory.getlogger(ProductServiceFallbackFactory.class)@Overridepublic ProductService create(Throwable throwable){logger.error("product-service 服务的selectProductById方法出现异常,异常信息如下:"+ throwable);return new Product(id,"托底",1,2666D);}}
声明需要调用的服务
@FeignClient("product-service",fallbackFactory = ProductServiceFallbackFactory.class)public interface ProductService{/***根据主键查询商品/@GetMapping("/product/{id}")Product selectProductById(@PathVariable("id") Integer id);}
