接上:
https://blog.csdn.net/wdz985721191/article/details/121713020
引入依赖:
在所需要的服务中引入依赖
<!--fegin--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!--sentinel--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>
配置文件:
# 开启feign对sentinel的支持 feign: sentinel: enabled: true
方式一:
创建容错类:实现Feign接口即可
package wdz.order.feign.fallback; import org.springframework.stereotype.Service; import wdz.common.model.Product; import wdz.order.feign.FeignProductService; import java.math.BigDecimal; /** * 产品服务模块容错类 * 实现feign接口,并实现所有接口, * 远程失败后,进入当前类中的同名方法中,执行容错逻辑 */ @Service public class FallbackProduct implements FeignProductService { @Override public Product findById(Long id) { Product product = new Product(); product.setId(-1L); product.setName("远程调用失败,容错逻辑"); product.setPrice(BigDecimal.ZERO); product.setStock(0); return product; } }
feign接口:
/** * fallback 用于指定远程异常返回类 */ @FeignClient(value = "wdz-product",fallback = FallbackProduct.class) public interface FeignProductService { @RequestMapping("/query/{id}") Product findById(@PathVariable Long id); }
此处代码逻辑处理与hystrix与feign整合类似
由于容错配置之后无异常,对业务排错有一定的阻碍,
方式二:
使用fallbackFactory的方式,两种方式只用一种即可
实现代码:
package wdz.order.feign.fallback;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Service;
import wdz.common.model.Product;
import wdz.order.feign.FeignProductService;
import java.math.BigDecimal;
/**
* 容错类,实现FallbackFactory<对应的Feign接口>
*/
@Service
public class FallbackProductException implements FallbackFactory<FeignProductService> {
@Override
public FeignProductService create(Throwable throwable) {
// 异常处理
System.out.println("异常处理");
return new FeignProductService() {
@Override
public Product findById(Long id) {
Product product = new Product();
product.setId(-1L);
product.setName("远程调用失败,容错逻辑");
product.setPrice(BigDecimal.ZERO);
product.setStock(0);
return product;
}
};
}
}