Fegin 整合 Sentinel 实现容错|学习笔记

简介: 快速学习 Fegin 整合 Sentinel 实现容错

开发者学堂课程【全面讲解 Spring Cloud Alibaba 技术栈(知识精讲+项目实战)第二阶段Fegin 整合 Sentinel 实现容错】学习笔记与课程紧密联系,让用户快速学习知识

课程地址https://developer.aliyun.com/learning/course/684/detail/11883


Fegin 整合 Sentinel 实现容错

 

如何用 Fegin 整合 Sentinel 实现服务容错

这个过程大概需要六个步骤:

1.引入 Sentinel 的依赖

这个步骤已经处理完,找到 Order,打开 pom文件,Sentinel 的依赖已经存在。

<!--sentinel 客户端-->

<dependency>

<groupId>com.alibaba.cloud<groupId>

<artifactId>spring-cloud-starter-alibaba-sentinel<artifactId>

</dependency>

2.在配置文件中开启Feign对Sentinel的支持

找到配置文件 application,在最下面加入 Feign 对 Sentinel 的支持。

Feign:

Sentinel:

Enabled:ture

核心思想:

找到 Fegin 所在的接口,在 service 中找到 productservice,当 Feign 进行远程调用的过程中可能会出现问题,需要为它提供一个容错的类,在容错类中写套一一模一样的方法,一旦这个方法失败,进入容错类中的方法。

3.创建容错类

在 service 下创建 Fallback 的包,

新建一个 ProductServiceFallback。

需要实现 Fegin 所在的接口,并去使用接口中的所有方法,一旦 Feign 远程调用出现问题,就会进入当前类中同名方法,执行容错逻辑,把它放入容器里面,再编写容错逻辑。

//这是一个容错类,需要实现 Fegin 所在的接口,并去实现接口中的所有方法。

//一旦 Fegin 远程调用出现问题了,就会进入当前类中同名方法,执行容错逻辑。

@service

Public class pripoductServiceFallback implements ProductService (

@Override

Public product findBypid(Integet pid) (

//容错逻辑

Product product=new Product();

Product.netpanma(“远程调用商品微服务出现异常了,进入了容错逻辑”);

Return product;

4.为Fegin容器的接口指定容错类

value 用于指定调用 nacos 下哪个微服务,fallback 用于指定当前 fegin 接口的容错类。

@FeignClient(

Value=”service-product”;

Fallback=ProductServiceFallback.class

5.调用之前,做一个判断

打开ordercontroller.

product product=productService.findpid(pid);

在调用远程结束以后,做一个判断

If  (product.getpid  == -100) {

Order order=new order();

Order.setold(-100L);

Order.setPname(“下单失败”);

Return order

将 order 和 product 都运行起来。

6.测试

打开 order 下一个订单,现在访问刷新并无异常。

{

“cid”: 16.

“uid”: 1.

“username”:测试用户

“pid”: 1.

“pname”:”小米”.

“ppcice”:1000

“number”:1

}

停掉 product application,观察是否能进入容错逻辑,如下图,已经进入容错逻辑。

{

“cid”:-100.

“uid”:null.

“username”:null.

“pid”:null.

“pname”:”下单失败”.

“ppcice”:null.

“number”:null

}

相关文章
|
Java 开发者 Sentinel
Sentinel 手动实现限流规则 | 学习笔记
快速学习 Sentinel 手动实现限流规则
365 0
|
Java Nacos Sentinel
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(九)Nacos+Sentinel+Seata
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(九)Nacos+Sentinel+Seata
2441 0
|
SpringCloudAlibaba 监控 Java
SpringCloud Alibaba Sentinel实现熔断与限流--学习笔记
SpringCloud Alibaba Sentinel实现熔断与限流--学习笔记
309 0
|
监控 安全 Java
|
自然语言处理 Java 数据安全/隐私保护
Springcloud之Sentinel服务容错
Springcloud之Sentinel服务容错
|
消息中间件 缓存 监控
|
Kubernetes 负载均衡 Cloud Native
Sentinel 2.0 :流量治理全面升级 | 学习笔记
快速学习 Sentinel 2.0 :流量治理全面升级
Sentinel 2.0 :流量治理全面升级 | 学习笔记
|
监控 Dubbo Java
Sentinel 使用入门|学习笔记
快速学习 Sentinel 使用入门
Sentinel 使用入门|学习笔记
|
Java API 开发者
Sentinel 规则持久化|学习笔记
快速学习 Sentinel 规则持久化
Sentinel 规则持久化|学习笔记
|
Java 开发者 Sentinel
Sentinel 概念和功能|学习笔记
快速学习 Sentinel 概念和功能
Sentinel 概念和功能|学习笔记