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、编写服务提供者

1.2、集成feign


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);
}

2、整合Feign和Sentinel
2.1、开启Feign的Sentinel功能
feign:
sentinel:
enabled: true #开启Feign的Sentinel功能

2.2、服务降级实现的选择
FallbackClass:无法对选程调用的异常做处理
FallbackFactory:可以对远程调用的异常做处理,我们选择这种
3、测试
