OpenFeign整合我们的Sentinel
- 第一步加配置: 在tulingvip05-ms-alibaba-feignwithsentinel-order上 pom.xml中添加配置
<dependency>
<groupId>com.tuling</groupId>
<artifactId>03-ms-alibaba-feign-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--加入sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--加入actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 第二步:在我们的Feign的声明式接口上添加fallback属性或者 fallbackFactory属性
1)为我们添加fallback属性的api
@FeignClient(name = "product-center",fallback = ProductCenterFeignApiWithSentinelFallback.class)
/*
@FeignClient(name = "product-center",fallbackFactory = ProductCenterFeignApiWithSentielFallbackFactory.class)
*/
public interface ProductCenterFeignApiWithSentinel {
/**
* 声明式接口,远程调用http://product-center/selectProductInfoById/{productNo}
* @param productNo
* @return
*/
@RequestMapping("/selectProductInfoById/{productNo}")
ProductInfo selectProductInfoById(@PathVariable("productNo") String productNo);
}
我们feign的限流降级接口(通过fallback没有办法获取到异常的)
@Component
public class ProductCenterFeignApiWithSentinelFallback implements ProductCenterFeignApiWithSentinel {
@Override
public ProductInfo selectProductInfoById(String productNo) {
ProductInfo productInfo = new ProductInfo();
productInfo.setProductName("默认商品");
return productInfo;
}
}
2)通过FallbackFactory属性可以处理我们的异常
/*
@FeignClient(name = "product-center",fallback = ProductCenterFeignApiWithSentinelFallback.class)*/
@FeignClient(name = "product-center",fallbackFactory = ProductCenterFeignApiWithSentielFallbackFactory.class)
public interface ProductCenterFeignApiWithSentinel {
/**
* 声明式接口,远程调用http://product-center/selectProductInfoById/{productNo}
* @param productNo
* @return
*/
@RequestMapping("/selectProductInfoById/{productNo}")
ProductInfo selectProductInfoById(@PathVariable("productNo") String productNo);
}
@Component
@Slf4j
public class ProductCenterFeignApiWithSentielFallbackFactory implements FallbackFactory<ProductCenterFeignApiWithSentinel> {
@Override
public ProductCenterFeignApiWithSentinel create(Throwable throwable) {
return new ProductCenterFeignApiWithSentinel(){
@Override
public ProductInfo selectProductInfoById(String productNo) {
ProductInfo productInfo = new ProductInfo();
if (throwable instanceof FlowException) {
log.error("流控了....{}",throwable.getMessage());
productInfo.setProductName("我是被流控的默认商品");
}else {
log.error("降级了....{}",throwable.getMessage());
productInfo.setProductName("我是被降级的默认商品");
}
return productInfo;
}
};
}
}