sentinel–基础–5.1–隔离和降级–整合feign
代码位置
https://gitee.com/DanShenGuiZu/learnDemo/tree/master/sentinel_learn/demo01
https://gitee.com/DanShenGuiZu/learnDemo/tree/master/sentinel_learn/demo2
1、准备工作
1.1、编写服务提供者
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/512f9b27606f4a17b2284af75073ace3.png#pic_center)
1.2、集成feign
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/d1399caccee04ade8eae16a7823ffba4.png#pic_center)
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/becacac323ad47e38e907d1734c469c8.png#pic_center)
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- openfeign 依赖 begin-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>4.1.1</version>
</dependency>
<!-- openfeign 依赖 end-->
User_Feign
package com.example.demo2.business.feignClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(value = "demo01",fallbackFactory = UserFallbackFactory.class)
public interface User_Feign {
@RequestMapping("/getUserId/{id}")
Integer getUserId(@PathVariable("id") Integer id);
}
package com.example.demo2.business.feignClient;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
/**
* 这里是失败降级的处理逻辑
* @author <a href="920786312@qq.com">周飞</a>
* @since 2024/5/25 19:24
*/
@Component
public class UserFallbackFactory implements FallbackFactory<User_Feign> {
@Override
public User_Feign create(Throwable cause) {
return new User_Feign() {
@Override
public Integer getUserId(Integer id) {
System.out.println("查询异常,默认返回0");
return 0;
}
};
}
}
HelloController
@Autowired
private User_Feign userFeign;
@RequestMapping("/getUserId/{id}")
public Integer getUserId(@PathVariable("id") Integer id) {
return userFeign.getUserId(id);
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/552a484b0bf94fa596568cd374505164.png#pic_center)
2、整合Feign和Sentinel
2.1、开启Feign的Sentinel功能
feign:
sentinel:
enabled: true #开启Feign的Sentinel功能
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/3bb6f6b17a02487a8eeadf5d3fa4b55f.png#pic_center)
2.2、服务降级实现的选择
FallbackClass:无法对选程调用的异常做处理
FallbackFactory:可以对远程调用的异常做处理,我们选择这种
3、测试
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/da7558161c8d44b2a1ffb80fcb4fa55a.png#pic_center)